diff --git a/crates/tinywallet-bus/src/lib_tests.rs b/crates/tinywallet-bus/src/lib_tests.rs index 82402dce..6d9a12fc 100644 --- a/crates/tinywallet-bus/src/lib_tests.rs +++ b/crates/tinywallet-bus/src/lib_tests.rs @@ -110,7 +110,7 @@ fn network_request_keeps_legacy_json_and_omits_unset_endpoint_url() { #[test] fn the_contract_accepts_its_own_version_and_newer_minors() { - assert_eq!(CONTRACT_VERSION, (1, 15)); + assert_eq!(CONTRACT_VERSION, (1, 16)); assert!(is_compatible(CONTRACT_VERSION)); assert!(is_compatible((CONTRACT_VERSION.0, CONTRACT_VERSION.1 + 1))); assert!(!is_compatible((CONTRACT_VERSION.0 + 1, 0))); @@ -146,7 +146,7 @@ fn the_method_list_is_sorted_complete_and_free_of_duplicates() { METHODS, "sorted dispatch order, no repeats" ); - assert_eq!(METHODS.len(), 39); + assert_eq!(METHODS.len(), 40); for member in [ names::methods::ATTACH_SIGNATURE, names::methods::BUILD_UNSIGNED, @@ -188,6 +188,7 @@ fn the_method_list_is_sorted_complete_and_free_of_duplicates() { names::methods::X402_UPDATE_BUDGET, names::methods::X402_CLOSE, names::methods::X402_CONFIGURE, + names::methods::X402_SIGN_IN, ] { assert!( METHODS.contains(&member), @@ -292,7 +293,7 @@ fn native_wallet_members_are_additive_and_use_one_typed_argument() { methods::NATIVE_WALLET_TX_RECEIPT, methods::NATIVE_WALLET_LOOKUP_TX, ]; - assert_eq!(METHODS.len(), 39); + assert_eq!(METHODS.len(), 40); assert!(native_members.iter().all(|member| METHODS.contains(member))); assert_eq!(HOST_METHODS.len(), 6); assert!(HOST_METHODS.contains(&host_methods::AUTHORIZE_NATIVE_WALLET_EXECUTION)); @@ -443,3 +444,9 @@ fn token_balance_rows_serialize_in_camel_case_with_the_mint() { row ); } + +#[test] +fn signing_in_with_x_is_confidential() { + // It carries the EVM recovery phrase into the module, like a payment. + assert!(CONFIDENTIAL_METHODS.contains(&names::methods::X402_SIGN_IN)); +} diff --git a/crates/tinywallet-bus/src/names/mod.rs b/crates/tinywallet-bus/src/names/mod.rs index 2d6acdad..2040b308 100644 --- a/crates/tinywallet-bus/src/names/mod.rs +++ b/crates/tinywallet-bus/src/names/mod.rs @@ -111,6 +111,9 @@ pub mod methods { pub const ENCODE_ERC20_TRANSFER: &str = "EncodeErc20Transfer"; /// Records a retry result and commits or releases its module reservation. pub const X402_RECORD_PAYMENT: &str = "X402RecordPayment"; + /// Signs an x402 `sign-in-with-x` challenge for the requested host with + /// the EVM account. Contract 1.16. + pub const X402_SIGN_IN: &str = "X402SignIn"; /// Reports ledger totals and spending limits. pub const X402_SPENDING_SUMMARY: &str = "X402SpendingSummary"; /// Reports ledger totals, counts and spending limits for host projection. @@ -163,6 +166,7 @@ pub const METHODS: &[&str] = &[ methods::X402_LIST_PAYMENTS, methods::X402_PREPARE_PAYMENT, methods::X402_RECORD_PAYMENT, + methods::X402_SIGN_IN, methods::X402_SPENDING_SUMMARY, methods::X402_SPENDING_SUMMARY_DETAILED, methods::X402_UPDATE_BUDGET, @@ -184,4 +188,5 @@ pub const CONFIDENTIAL_METHODS: &[&str] = &[ methods::SIGN_TRANSACTION, methods::WEB3_EXECUTE, methods::X402_PREPARE_PAYMENT, + methods::X402_SIGN_IN, ]; diff --git a/crates/tinywallet-bus/src/storage.rs b/crates/tinywallet-bus/src/storage.rs index 2b1bba14..f2344415 100644 --- a/crates/tinywallet-bus/src/storage.rs +++ b/crates/tinywallet-bus/src/storage.rs @@ -79,6 +79,9 @@ pub struct StoredPaymentRecord { /// The conversation thread, if any. #[serde(default, skip_serializing_if = "Option::is_none")] pub thread_id: Option, + /// The x402 scheme the payment was signed under. Absent means `exact`. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub scheme: Option, /// The budget hold this entry committed, if any. #[serde(default, skip_serializing_if = "Option::is_none")] pub committed_hold: Option, diff --git a/crates/tinywallet-bus/src/version/mod.rs b/crates/tinywallet-bus/src/version/mod.rs index 62fb4fd2..a670c4f7 100644 --- a/crates/tinywallet-bus/src/version/mod.rs +++ b/crates/tinywallet-bus/src/version/mod.rs @@ -1,7 +1,7 @@ //! The `TinyWallet` `TinyBus` contract version and its binding rule. /// The wire contract version this crate defines. -pub const CONTRACT_VERSION: (u32, u32) = (1, 15); +pub const CONTRACT_VERSION: (u32, u32) = (1, 16); /// Returns whether a host using [`CONTRACT_VERSION`] can bind to `module`. /// diff --git a/crates/tinywallet-bus/src/wire/host.rs b/crates/tinywallet-bus/src/wire/host.rs index 7da6b4c9..2c152a2a 100644 --- a/crates/tinywallet-bus/src/wire/host.rs +++ b/crates/tinywallet-bus/src/wire/host.rs @@ -361,12 +361,20 @@ pub struct AuthorizeX402PaymentRequest { pub asset: String, /// Payment recipient. pub recipient: String, - /// Exact amount in token atomic units. + /// Amount in token atomic units that the signed authorization allows: the + /// exact price for `exact`, the most that can be charged for `upto`. A + /// host cap compares against this value. pub amount_atomic: u64, /// Conversation owner used to route approval to the initiating client. /// Older hosts omit this field and retain their existing approval flow. #[serde(default, skip_serializing_if = "Option::is_none")] pub owner: Option, + /// The x402 scheme the payment is signed under: `"exact"`, or `"upto"`, + /// where `amount_atomic` is a ceiling and the server charges what it + /// used, from zero up to it. Absent from older modules, which sign only + /// `exact`. Contract 1.16. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub scheme: Option, } /// Request module-owned parsing and signing for a 402 challenge. @@ -388,6 +396,13 @@ pub struct X402PreparePaymentRequest { /// Older hosts omit this field and keep sending only `secret`. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub additional_secrets: Vec, + /// Pay only on this network. A CAIP-2 chain id (`eip155:8453`) must equal + /// the option's network; a CAIP-2 namespace without a colon (`eip155`, + /// `solana`) matches every chain in it. When no option matches, the + /// request is refused before anything is reserved or signed. `None`, and + /// older hosts that omit the field, keep the module's own preference. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub network: Option, } /// Payment proof and pending-ledger handle returned to the host for retry. @@ -408,6 +423,35 @@ pub struct X402PreparePaymentResponse { pub network: String, } +/// Sign an x402 `sign-in-with-x` challenge with the wallet's EVM account. +/// +/// The module signs only an EIP-4361 sign-in built from the challenge, and +/// only when its `domain` is the host of `url`, its `uri` and `resources` are +/// HTTPS on that origin, and its `expirationTime` is still ahead. It is not a +/// way to sign other text. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct X402SignInRequest { + /// The URL whose 402 response carried the challenge. + pub url: String, + /// Raw `PAYMENT-REQUIRED` header value (base64 JSON) of that response. + pub payment_required: String, + /// The EVM wallet material, consumed only inside the confidential call. + pub secret: SecretMaterial, +} + +/// The signed sign-in for the host's retry. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct X402SignInResponse { + /// Value for the `SIGN-IN-WITH-X` request header. + pub header: String, + /// The account that signed in, EIP-55 checksummed. + pub address: String, + /// The CAIP-2 chain the sign-in names, such as `eip155:8453`. + pub chain_id: String, +} + /// Record the outcome after the host retries with the module-built proof. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(deny_unknown_fields)] diff --git a/crates/tinywallet-bus/src/wire/mod.rs b/crates/tinywallet-bus/src/wire/mod.rs index abae3c28..35f0d7b4 100644 --- a/crates/tinywallet-bus/src/wire/mod.rs +++ b/crates/tinywallet-bus/src/wire/mod.rs @@ -51,8 +51,8 @@ pub use host::{ Web3ServiceHandle, X402CloseRequest, X402ConfigResponse, X402ConfigureRequest, X402DetailedSpendingSummary, X402ListPaymentsRequest, X402ListPaymentsResponse, X402PaymentRecord, X402PaymentStatus, X402PreparePaymentRequest, X402PreparePaymentResponse, - X402RecordPaymentRequest, X402ServiceHandle, X402SpendingSummary, X402SummaryRequest, - X402UpdateBudgetRequest, + X402RecordPaymentRequest, X402ServiceHandle, X402SignInRequest, X402SignInResponse, + X402SpendingSummary, X402SummaryRequest, X402UpdateBudgetRequest, }; pub use wallet::{ BalanceInfo, ChainStatus, DeriveMnemonicSeedRequest, DeriveMnemonicSeedResponse, diff --git a/crates/tinywallet-bus/src/wire/mod_tests.rs b/crates/tinywallet-bus/src/wire/mod_tests.rs index d3be6b2d..aaa1162a 100644 --- a/crates/tinywallet-bus/src/wire/mod_tests.rs +++ b/crates/tinywallet-bus/src/wire/mod_tests.rs @@ -397,3 +397,39 @@ fn x402_chain_secret_extension_preserves_legacy_serialization() { let request: super::X402PreparePaymentRequest = serde_json::from_value(legacy.clone()).unwrap(); assert_eq!(serde_json::to_value(request).unwrap(), legacy); } + +#[test] +fn an_x402_authorization_names_its_scheme_and_older_hosts_still_parse_it() { + let request = super::AuthorizeX402PaymentRequest { + url: "https://twitr.sh/api/tools/x_search".into(), + network: "eip155:8453".into(), + asset: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913".into(), + recipient: "0xb5194A98DbDBb7028B585Db26B972e7F0F3f826A".into(), + amount_atomic: 3600, + owner: None, + scheme: Some("upto".into()), + }; + let encoded = serde_json::to_value(&request).unwrap(); + assert_eq!(encoded["scheme"], "upto"); + assert_eq!( + serde_json::from_value::(encoded).unwrap(), + request + ); + + let legacy = json!({ + "url": "https://x", "network": "eip155:8453", "asset": "a", + "recipient": "r", "amount_atomic": 1 + }); + let parsed: super::AuthorizeX402PaymentRequest = serde_json::from_value(legacy).unwrap(); + assert_eq!(parsed.scheme, None); + let unnamed = super::AuthorizeX402PaymentRequest { + scheme: None, + ..parsed + }; + assert!( + serde_json::to_value(&unnamed) + .unwrap() + .get("scheme") + .is_none() + ); +} diff --git a/crates/tinywallet-module/src/service/mod.rs b/crates/tinywallet-module/src/service/mod.rs index bbc5e206..557ee587 100644 --- a/crates/tinywallet-module/src/service/mod.rs +++ b/crates/tinywallet-module/src/service/mod.rs @@ -303,6 +303,17 @@ impl Wallet { x402.prepare(request).await.map_err(x402_operation_failed) } + /// Sign an x402 `sign-in-with-x` challenge with the EVM secret. Only a + /// sign-in for the requested host is signed; anything else is refused + /// before the key is used. + #[tinybus(confidential)] + async fn x402_sign_in( + &self, + request: tinywallet_bus::wire::X402SignInRequest, + ) -> BusResult { + x402::sign_in(request).await.map_err(x402_operation_failed) + } + /// Open or replace the active Web3 quote service after the host establishes /// the account context. Replacing it waits for in-flight executions and /// discards every quote tied to the previous credentials. @@ -1571,6 +1582,7 @@ mod exports { "X402UpdateBudget", "X402Configure", "X402Close", + "X402SignIn", ], signals = [], requires = [], diff --git a/crates/tinywallet-module/src/service/mod_tests.rs b/crates/tinywallet-module/src/service/mod_tests.rs index 800a83d0..6ba24d30 100644 --- a/crates/tinywallet-module/src/service/mod_tests.rs +++ b/crates/tinywallet-module/src/service/mod_tests.rs @@ -1620,6 +1620,7 @@ async fn user_scoped_operations_fail_closed_before_configuration() { owner: None, additional_secrets: Vec::new(), secret: secret(Chain::Evm, "m/44'/60'/0'/0/0"), + network: None, }) .await .is_err() @@ -1660,3 +1661,49 @@ async fn user_scoped_operations_fail_closed_before_configuration() { .is_err() ); } + +/// Every bus error the service raises names its own error, so a host can +/// tell a refused approval from an unreachable host or a bad input, and +/// carries the message it was given. +#[test] +fn each_bus_error_names_its_kind_and_keeps_its_message() { + let named = |error: super::BusError| match error { + super::BusError::MethodFailed { name, message } => (name, message), + other => panic!("not a method failure: {other:?}"), + }; + let (name, _) = named(super::host_unavailable()); + assert_eq!(name, "ai.tinyhumans.tinywallet.Error.HostUnavailable"); + for (error, kind) in [ + (super::host_call_failed("m".into()), "HostCallFailed"), + (super::invalid_input("m".into()), "InvalidInput"), + ( + super::web3_operation_failed("m".into()), + "Web3OperationFailed", + ), + ( + super::x402_operation_failed("m".into()), + "X402OperationFailed", + ), + ( + super::native_wallet_operation_failed("m".into()), + "NativeWalletOperationFailed", + ), + (super::host_build_failed("m".into()), "BuildFailed"), + ] { + let (name, message) = named(error); + assert!(name.ends_with(kind), "{name} is not {kind}"); + assert_eq!(message, "m"); + } +} + +#[test] +fn a_failure_reads_as_its_message() { + assert_eq!( + super::failure_message(super::Failure::InvalidInput("bad".into())), + "bad" + ); + assert_eq!( + super::failure_message(super::Failure::BuildFailed("broke".into())), + "broke" + ); +} diff --git a/crates/tinywallet-module/src/service/x402.rs b/crates/tinywallet-module/src/service/x402.rs index 233cdaf8..40bb044a 100644 --- a/crates/tinywallet-module/src/service/x402.rs +++ b/crates/tinywallet-module/src/service/x402.rs @@ -9,14 +9,17 @@ use tinywallet_bus::wire::{ AuthorizeX402PaymentRequest, SecretMaterial, X402ConfigResponse, X402DetailedSpendingSummary, X402ListPaymentsRequest, X402ListPaymentsResponse, X402PaymentRecord, X402PaymentStatus, X402PreparePaymentRequest, X402PreparePaymentResponse, X402RecordPaymentRequest, - X402ServiceHandle, X402SpendingSummary, X402SummaryRequest, X402UpdateBudgetRequest, + X402ServiceHandle, X402SignInRequest, X402SignInResponse, X402SpendingSummary, + X402SummaryRequest, X402UpdateBudgetRequest, +}; +use tinywallet_x402::crypto::{ + CryptoPayments, PaymentAccount, PaymentSigner, SignScheme, sign_in_with_x, }; -use tinywallet_x402::crypto::{CryptoPayments, PaymentAccount, PaymentSigner, SignScheme}; use tinywallet_x402::ledger::{self, PaymentRecord, PaymentStatus, SpendingBudget}; use tinywallet_x402::protocol::{ - handle_402_and_pay_authorized, parse_settlement_response, settles, + handle_402_and_pay_on_network, parse_402_headers, parse_settlement_response, settled_amount, }; -use tinywallet_x402::wire::PaymentChain; +use tinywallet_x402::wire::{PaymentChain, SettlementResponse}; use super::host::HostCallbacks; use super::web3::{HostTransport, with_x402_execution_context}; @@ -198,6 +201,7 @@ impl X402Runtime { let thread_id = request.owner.as_ref().map(|owner| owner.thread_id.clone()); let owner = request.owner.clone(); let url = request.url.clone(); + let network = request.network.clone(); let callbacks = self.callbacks.clone(); let (proof, _admission) = with_x402_execution_context(request.owner, secrets, async { let signer: Arc = Arc::new(ModulePaymentSigner); @@ -211,10 +215,11 @@ impl X402Runtime { .await .map_err(|error| error.to_string())?; admission.ensure_capacity()?; - let proof = handle_402_and_pay_authorized( + let proof = handle_402_and_pay_on_network( &builder, &headers, &url, + network.as_deref(), move |url, requirement, _chain, amount_atomic| async move { let authorization = callbacks .authorize_x402_payment(AuthorizeX402PaymentRequest { @@ -224,6 +229,7 @@ impl X402Runtime { recipient: requirement.pay_to, amount_atomic, owner: owner.clone(), + scheme: Some(requirement.scheme), }) .await?; if authorization.approved { @@ -256,24 +262,7 @@ impl X402Runtime { recipient: proof.recipient.clone(), network: proof.network.clone(), }; - let record = PaymentRecord { - id: payment_id, - url: proof.url.clone(), - asset: proof.asset.clone(), - amount_atomic: proof.amount_atomic, - amount_display: tinywallet_x402::ledger::format_usdc(proof.amount_atomic), - recipient: proof.recipient.clone(), - network: proof.network.clone(), - tx_signature: None, - status: PaymentStatus::Pending, - timestamp: Utc::now(), - authorization_valid_until: proof.authorization_valid_until, - solana_last_valid_block_height: proof.solana_last_valid_block_height, - authorization_expired_at: None, - authorization_expiry_observed_height: None, - session_id: self.config.session_id.clone(), - thread_id, - }; + let record = pending_payment_record(&proof, payment_id, &self.config.session_id, thread_id); proof .reservation .commit_durable(record) @@ -306,56 +295,17 @@ impl X402Runtime { /// retries the paid request. pub(crate) fn record(&self, request: X402RecordPaymentRequest) -> Result<(), String> { self.require_handle(&request.service)?; - let pending = ledger::with_ledger(|ledger| ledger.payment(&request.payment_id).cloned())? - .ok_or_else(|| "x402 payment handle was missing".to_string())?; - if pending.status == PaymentStatus::Settled { - // A reply may be lost after the durable transition; replaying the - // same receipt is an idempotent acknowledgment. - return Ok(()); - } - let legacy_expired = - pending.status == PaymentStatus::Failed && pending.authorization_valid_until.is_some(); - if pending.status != PaymentStatus::Pending && !legacy_expired { - return Err("x402 payment handle was missing or expired".to_string()); - } - let receipt = request - .settlement_response + let X402RecordPaymentRequest { + payment_id, + settlement_response, + .. + } = request; + let receipt = settlement_response .as_deref() - .and_then(|value| parse_settlement_response(value).ok()) - .filter(|receipt| settles(receipt, &pending.network, pending.amount_atomic)); - let status = if receipt.is_some() { - PaymentStatus::Settled - } else { - // Neither a failed HTTP response nor an elapsed authorization - // deadline proves that a previously returned proof did not settle. - PaymentStatus::Pending - }; - let tx_signature = receipt - .filter(|receipt| !receipt.transaction.is_empty()) - .map(|receipt| receipt.transaction); - if status == pending.status { - return Ok(()); - } - let record = PaymentRecord { - id: request.payment_id, - url: pending.url, - asset: pending.asset, - amount_atomic: pending.amount_atomic, - amount_display: pending.amount_display, - recipient: pending.recipient, - network: pending.network, - tx_signature, - status, - timestamp: chrono::Utc::now(), - authorization_valid_until: pending.authorization_valid_until, - solana_last_valid_block_height: pending.solana_last_valid_block_height, - authorization_expired_at: pending.authorization_expired_at, - authorization_expiry_observed_height: pending.authorization_expiry_observed_height, - session_id: pending.session_id, - thread_id: pending.thread_id, - }; - ledger::with_ledger_mut(|ledger| ledger.try_record_payment(record))??; - Ok(()) + .and_then(|value| parse_settlement_response(value).ok()); + // Read, decide and append under the one ledger lock, so two receipts + // for the same payment cannot both settle it. + ledger::with_ledger_mut(|ledger| settle(ledger, &payment_id, receipt))? } /// Read the module-owned budget totals and currently held reservations. @@ -443,6 +393,128 @@ impl X402Runtime { } } +/// Move payment `payment_id` to what `receipt` proves, on a ledger the caller +/// holds locked: the latest state is re-read (another writer may have settled +/// it), compared, and the transition appended in the same critical section. +fn settle( + ledger: &mut ledger::PaymentLedger, + payment_id: &str, + receipt: Option, +) -> Result<(), String> { + ledger.refresh()?; + let pending = ledger + .payment(payment_id) + .cloned() + .ok_or_else(|| "x402 payment handle was missing".to_string())?; + if pending.status == PaymentStatus::Settled { + return same_charge(&pending, receipt.as_ref()); + } + let legacy_expired = + pending.status == PaymentStatus::Failed && pending.authorization_valid_until.is_some(); + if pending.status != PaymentStatus::Pending && !legacy_expired { + return Err("x402 payment handle was missing or expired".to_string()); + } + // An `upto` payment is pending at its signed ceiling; its receipt + // reports what was charged, which is what the ledger keeps. + let receipt = receipt.and_then(|receipt| { + settled_amount( + &receipt, + &pending.network, + pending.scheme.as_deref(), + pending.amount_atomic, + ) + .map(|charged| (receipt, charged)) + }); + let amount_atomic = receipt + .as_ref() + .map_or(pending.amount_atomic, |(_, charged)| *charged); + let status = if receipt.is_some() { + PaymentStatus::Settled + } else { + // Neither a failed HTTP response nor an elapsed authorization + // deadline proves that a previously returned proof did not settle. + PaymentStatus::Pending + }; + let tx_signature = receipt + .filter(|(receipt, _)| !receipt.transaction.is_empty()) + .map(|(receipt, _)| receipt.transaction); + if status == pending.status { + return Ok(()); + } + let record = PaymentRecord { + id: payment_id.to_string(), + url: pending.url, + asset: pending.asset, + amount_display: if amount_atomic == pending.amount_atomic { + pending.amount_display + } else { + tinywallet_x402::ledger::format_usdc(amount_atomic) + }, + amount_atomic, + recipient: pending.recipient, + network: pending.network, + tx_signature, + status, + timestamp: chrono::Utc::now(), + authorization_valid_until: pending.authorization_valid_until, + solana_last_valid_block_height: pending.solana_last_valid_block_height, + authorization_expired_at: pending.authorization_expired_at, + authorization_expiry_observed_height: pending.authorization_expiry_observed_height, + session_id: pending.session_id, + thread_id: pending.thread_id, + scheme: pending.scheme, + }; + ledger.try_record_payment(record) +} + +/// A reply may be lost after a payment settled, so the same receipt can come +/// back: that is acknowledged. A receipt that settles it for another amount +/// is refused, and the ledger keeps the first. +fn same_charge( + settled: &PaymentRecord, + receipt: Option<&SettlementResponse>, +) -> Result<(), String> { + let reported = receipt + .filter(|receipt| receipt.success && receipt.network == settled.network) + .and_then(|receipt| receipt.amount.as_deref()); + match reported { + Some(amount) if amount.parse::().ok() != Some(settled.amount_atomic) => Err(format!( + "x402 payment was already settled for {} atomic units; a receipt for {amount} was refused", + settled.amount_atomic + )), + _ => Ok(()), + } +} + +/// The ledger's pending record for a just-built payment: the amount signed +/// for (an `upto` ceiling until its receipt says otherwise) and the scheme. +fn pending_payment_record( + proof: &tinywallet_x402::protocol::X402PaymentResult, + payment_id: String, + session_id: &str, + thread_id: Option, +) -> PaymentRecord { + PaymentRecord { + id: payment_id, + url: proof.url.clone(), + asset: proof.asset.clone(), + amount_atomic: proof.amount_atomic, + amount_display: tinywallet_x402::ledger::format_usdc(proof.amount_atomic), + recipient: proof.recipient.clone(), + network: proof.network.clone(), + tx_signature: None, + status: PaymentStatus::Pending, + timestamp: Utc::now(), + authorization_valid_until: proof.authorization_valid_until, + solana_last_valid_block_height: proof.solana_last_valid_block_height, + authorization_expired_at: None, + authorization_expiry_observed_height: None, + session_id: session_id.to_string(), + thread_id, + scheme: Some(proof.scheme.clone()), + } +} + fn payment_record_to_wire(record: PaymentRecord) -> X402PaymentRecord { let timestamp = |value: chrono::DateTime| { value.to_rfc3339_opts(chrono::SecondsFormat::AutoSi, true) @@ -548,6 +620,51 @@ impl PaymentSigner for ModulePaymentSigner { } } +/// Sign a `sign-in-with-x` challenge with the EVM secret in `request`. The +/// rules on what is signed live in `tinywallet_x402::crypto::sign_in_with_x`. +pub(crate) async fn sign_in(mut request: X402SignInRequest) -> Result { + let secret = std::mem::replace( + &mut request.secret, + SecretMaterial { + mnemonic: String::new(), + derivation_path: String::new(), + chain: tinywallet_bus::Chain::Evm, + }, + ); + let mut secrets = vec![secret]; + if secrets[0].chain != tinywallet_bus::Chain::Evm { + wipe_secrets(&mut secrets); + return Err("x402 sign-in needs the EVM wallet secret".to_string()); + } + let challenge = HeaderValue::from_str(&request.payment_required) + .map_err(|error| format!("invalid sign-in challenge header: {error}")) + .and_then(|value| { + let mut headers = HeaderMap::new(); + headers.insert(HeaderName::from_static("payment-required"), value); + parse_402_headers(&headers) + .map_err(|error| format!("invalid sign-in challenge: {error}")) + }); + let challenge = match challenge { + Ok(challenge) => challenge, + Err(error) => { + wipe_secrets(&mut secrets); + return Err(error); + } + }; + let url = request.url; + let proof = with_x402_execution_context(None, secrets, async { + sign_in_with_x(&ModulePaymentSigner, &challenge, &url) + .await + .map_err(|error| error.to_string()) + }) + .await?; + Ok(X402SignInResponse { + header: proof.header_value, + address: proof.address, + chain_id: proof.chain_id, + }) +} + fn wipe(secret: &mut SecretMaterial) { zeroize::Zeroize::zeroize(&mut secret.mnemonic); zeroize::Zeroize::zeroize(&mut secret.derivation_path); @@ -613,3 +730,11 @@ mod storage_bus_tests; #[cfg(test)] #[path = "x402_record_tests.rs"] mod record_tests; + +#[cfg(test)] +#[path = "x402_prepare_tests.rs"] +mod prepare_tests; + +#[cfg(test)] +#[path = "x402_sign_in_tests.rs"] +mod sign_in_tests; diff --git a/crates/tinywallet-module/src/service/x402_lifecycle_tests.rs b/crates/tinywallet-module/src/service/x402_lifecycle_tests.rs index 0485d410..63766710 100644 --- a/crates/tinywallet-module/src/service/x402_lifecycle_tests.rs +++ b/crates/tinywallet-module/src/service/x402_lifecycle_tests.rs @@ -112,6 +112,7 @@ async fn x402_service_lifecycle_records_approval_denial_and_cancellation() { }), additional_secrets: Vec::new(), secret: secret(tinywallet_bus::Chain::Evm), + network: None, }) .await .unwrap(); @@ -204,6 +205,7 @@ async fn x402_service_lifecycle_records_approval_denial_and_cancellation() { owner: None, additional_secrets: Vec::new(), secret: secret(tinywallet_bus::Chain::Solana), + network: None, }; let first_solana = wallet.x402_prepare_payment(prepare_solana()).await.unwrap(); let first_record = @@ -264,6 +266,7 @@ async fn x402_service_lifecycle_records_approval_denial_and_cancellation() { owner: None, additional_secrets: Vec::new(), secret: secret(tinywallet_bus::Chain::Evm), + network: None, }) .await .unwrap_err(); @@ -293,6 +296,7 @@ async fn x402_service_lifecycle_records_approval_denial_and_cancellation() { owner: None, additional_secrets: Vec::new(), secret: secret(tinywallet_bus::Chain::Evm), + network: None, }) .await }); @@ -353,6 +357,7 @@ async fn x402_service_lifecycle_records_approval_denial_and_cancellation() { owner: None, additional_secrets: Vec::new(), secret: secret(tinywallet_bus::Chain::Evm), + network: None, }) .await; assert!( diff --git a/crates/tinywallet-module/src/service/x402_prepare_tests.rs b/crates/tinywallet-module/src/service/x402_prepare_tests.rs new file mode 100644 index 00000000..6264f837 --- /dev/null +++ b/crates/tinywallet-module/src/service/x402_prepare_tests.rs @@ -0,0 +1,254 @@ +//! Tests for `X402PreparePayment` options: the caller's network pin, and +//! paying an `upto` challenge with its EIP-2612 gas-sponsoring permit. + +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use super::*; +use crate::service::x402::tests::{PaymentApprovalHost, secret}; + +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; + +use base64::Engine as _; +use base64::engine::general_purpose::STANDARD as BASE64; +use tinywallet_bus::wire::{X402CloseRequest, X402ConfigureRequest, X402PreparePaymentRequest}; + +/// A challenge offering Solana (the module's preference) and Ethereum USDC. +fn solana_and_evm_challenge() -> String { + BASE64.encode( + serde_json::to_vec(&serde_json::json!({ + "x402Version": 2, + "resource": {"url": "https://wallet.fixture.test/resource"}, + "accepts": [{ + "scheme": "exact", + "network": "solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp", + "amount": "100", + "asset": "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v", + "payTo": "9xQeWvG816bUx9EPfEZ6bJvT4G7M1S8qNnXvZ4QxS5V", + "maxTimeoutSeconds": 60, + "extra": {"feePayer": "9xQeWvG816bUx9EPfEZ6bJvT4G7M1S8qNnXvZ4QxS5V"} + }, { + "scheme": "exact", + "network": "eip155:1", + "amount": "100", + "asset": "0xA0b86991c6218b36c1d19d4a2e9eb0ce3606eb48", + "payTo": "0x3535353535353535353535353535353535353535", + "maxTimeoutSeconds": 60 + }] + })) + .unwrap(), + ) +} + +/// A wallet with a configured x402 service, served by an approving host. +struct Fixture { + wallet: crate::service::Wallet, + handle: tinywallet_bus::wire::X402ServiceHandle, + authorizations: Arc, + rpc_requests: Arc>>, + payment_requests: Arc>>, + broker_task: tokio::task::JoinHandle>, + /// The host's and the module's bus connections, kept open for the test. + _connections: (tinybus::Connection, tinybus::Connection), + _workspace: tempfile::TempDir, +} + +impl Fixture { + async fn start() -> Self { + let bus = tinybus::transport::memory::MemoryBus::new(); + let broker_task = tinybus::broker::Broker::new().spawn(bus.clone()); + let host = tinybus::Connection::connect(bus.connect().await.unwrap()) + .await + .unwrap(); + let authorizations = Arc::new(AtomicUsize::new(0)); + let rpc_requests = Arc::new(std::sync::Mutex::new(Vec::new())); + let payment_requests = Arc::new(std::sync::Mutex::new(Vec::new())); + host.serve_at( + crate::service::HOST_OBJECT_PATH.try_into().unwrap(), + PaymentApprovalHost { + approved: Arc::new(AtomicBool::new(true)), + authorizations: authorizations.clone(), + pause: Arc::new(AtomicBool::new(false)), + approval_started: Arc::new(tokio::sync::Notify::new()), + release_approval: Arc::new(tokio::sync::Notify::new()), + finalized_height: Arc::new(AtomicUsize::new(9)), + rpc_requests: rpc_requests.clone(), + payment_requests: payment_requests.clone(), + }, + ) + .await + .unwrap(); + host.request_name(crate::service::HOST_INTERFACE) + .await + .unwrap(); + let client = tinybus::Connection::connect(bus.connect().await.unwrap()) + .await + .unwrap(); + let wallet = crate::service::Wallet { + callbacks: Some(HostCallbacks::new(&client).unwrap()), + ..crate::service::Wallet::default() + }; + wallet + .callbacks + .as_ref() + .unwrap() + .set_test_ledger_storage(memory_ledger_storage()); + let workspace = tempfile::tempdir().unwrap(); + let handle = wallet + .x402_configure(X402ConfigureRequest { + config: X402ConfigResponse { + workspace_dir: workspace.path().display().to_string(), + session_id: "prepare-options".to_string(), + per_request_max_atomic: 10_000, + daily_max_atomic: 100_000, + monthly_max_atomic: 100_000, + }, + }) + .await + .unwrap(); + Self { + wallet, + handle, + authorizations, + rpc_requests, + payment_requests, + broker_task, + _connections: (host, client), + _workspace: workspace, + } + } + + fn prepare(&self, challenge: String, network: Option<&str>) -> X402PreparePaymentRequest { + X402PreparePaymentRequest { + service: self.handle.clone(), + url: "https://wallet.fixture.test/resource".to_string(), + payment_required: challenge, + owner: None, + secret: secret(tinywallet_bus::Chain::Evm), + additional_secrets: vec![secret(tinywallet_bus::Chain::Solana)], + network: network.map(Into::into), + } + } + + async fn close(self) { + self.wallet + .x402_close(X402CloseRequest { + service: self.handle.clone(), + }) + .await + .unwrap(); + self.broker_task.abort(); + } +} + +#[tokio::test] +async fn a_network_pin_chooses_the_paying_chain_and_refuses_an_absent_one() { + let _ledger_guard = LEDGER_TEST_LOCK.lock().await; + let fixture = Fixture::start().await; + let wallet = &fixture.wallet; + let prepare = |network: Option<&str>| fixture.prepare(solana_and_evm_challenge(), network); + + let unpinned = wallet.x402_prepare_payment(prepare(None)).await.unwrap(); + assert!( + unpinned.network.starts_with("solana:"), + "Solana stays preferred" + ); + for pin in ["eip155", "eip155:1"] { + let pinned = wallet + .x402_prepare_payment(prepare(Some(pin))) + .await + .unwrap(); + assert_eq!(pinned.network, "eip155:1", "{pin}"); + } + let last_approval = fixture + .payment_requests + .lock() + .unwrap() + .last() + .cloned() + .unwrap(); + assert_eq!(last_approval.scheme.as_deref(), Some("exact")); + + let approvals_before = fixture.authorizations.load(Ordering::SeqCst); + let error = wallet + .x402_prepare_payment(prepare(Some("eip155:8453"))) + .await + .unwrap_err(); + assert!( + format!("{error:?}").contains("no supported payment option on eip155:8453"), + "{error:?}" + ); + assert_eq!( + fixture.authorizations.load(Ordering::SeqCst), + approvals_before, + "an unmet pin never reaches host approval" + ); + fixture.close().await; +} + +/// The twitr.sh volume-tool challenge, re-homed on the fixture origin. +fn upto_challenge() -> String { + let mut challenge: serde_json::Value = serde_json::from_str(include_str!( + "../../../tinywallet-x402/src/wire/fixtures/twitr-upto-challenge.json" + )) + .unwrap(); + challenge["resource"]["url"] = "https://wallet.fixture.test/resource".into(); + BASE64.encode(serde_json::to_vec(&challenge).unwrap()) +} + +#[tokio::test] +async fn an_upto_challenge_is_authorized_and_held_at_its_ceiling() { + let _ledger_guard = LEDGER_TEST_LOCK.lock().await; + let fixture = Fixture::start().await; + + let prepared = fixture + .wallet + .x402_prepare_payment(fixture.prepare(upto_challenge(), Some("eip155:8453"))) + .await + .unwrap(); + + assert_eq!( + prepared.amount_atomic, 3600, + "the host caps the signed ceiling" + ); + assert_eq!(prepared.network, "eip155:8453"); + let approval = fixture.payment_requests.lock().unwrap()[0].clone(); + assert_eq!(approval.amount_atomic, 3600); + assert_eq!( + approval.scheme.as_deref(), + Some("upto"), + "the host is told the amount is a ceiling" + ); + let record = ledger::with_ledger(|ledger| ledger.payment(&prepared.payment_id).cloned()) + .unwrap() + .unwrap(); + assert_eq!(record.scheme.as_deref(), Some("upto")); + assert_eq!(record.amount_atomic, 3600); + + let payload: serde_json::Value = + serde_json::from_slice(&BASE64.decode(&prepared.payment_header).unwrap()).unwrap(); + let authorization = &payload["payload"]["permit2Authorization"]; + assert_eq!( + authorization["spender"], + "0x4020A4f3b7b90ccA423B9fabCc0CE57C6C240002" + ); + assert_eq!( + authorization["witness"]["facilitator"], + "0x4c934c63C786157Fefd990945b25eA60a0FB0205" + ); + // The fixture host reports a zero Permit2 allowance, so the module reads + // the token nonce over the host transport and signs an EIP-2612 permit. + let info = &payload["extensions"]["eip2612GasSponsoring"]["info"]; + assert_eq!(info["nonce"], "0"); + assert_eq!(info["amount"], "3600"); + assert!(info["signature"].as_str().unwrap().starts_with("0x")); + let calls: Vec = fixture + .rpc_requests + .lock() + .unwrap() + .iter() + .map(|(method, _)| method.clone()) + .collect(); + assert_eq!(calls.iter().filter(|m| *m == "eth_call").count(), 2); + fixture.close().await; +} diff --git a/crates/tinywallet-module/src/service/x402_record_tests.rs b/crates/tinywallet-module/src/service/x402_record_tests.rs index baa45958..155ade55 100644 --- a/crates/tinywallet-module/src/service/x402_record_tests.rs +++ b/crates/tinywallet-module/src/service/x402_record_tests.rs @@ -75,3 +75,175 @@ async fn record_settles_only_on_a_receipt_for_the_payments_network_and_amount() runtime.close(&handle).unwrap(); broker_task.abort(); } + +#[tokio::test] +async fn record_settles_an_upto_payment_at_the_amount_charged() { + let _ledger_guard = LEDGER_TEST_LOCK.lock().await; + let bus = tinybus::transport::memory::MemoryBus::new(); + let broker_task = tinybus::broker::Broker::new().spawn(bus.clone()); + let connection = tinybus::Connection::connect(bus.connect().await.unwrap()) + .await + .unwrap(); + let workspace = tempfile::tempdir().unwrap(); + let mut runtime = X402Runtime::new( + HostCallbacks::new(&connection).unwrap(), + X402ConfigResponse { + workspace_dir: workspace.path().display().to_string(), + session_id: "coverage-test".to_string(), + per_request_max_atomic: 10_000, + daily_max_atomic: 10_000, + monthly_max_atomic: 10_000, + }, + memory_ledger_storage(), + ) + .unwrap(); + let handle = runtime.handle(); + for (id, charged) in [("upto-a", 1200_u64), ("upto-b", 0)] { + let mut pending = pending_record(id, None); + pending.amount_atomic = 3600; + pending.network = "eip155:8453".to_string(); + pending.scheme = Some("upto".to_string()); + ledger::with_ledger_mut(|ledger| ledger.try_record_payment(pending)) + .unwrap() + .unwrap(); + + // Above the signed ceiling: not a settlement of this payment. + runtime + .record(X402RecordPaymentRequest { + service: handle.clone(), + payment_id: id.to_string(), + response_status: 200, + settlement_response: Some(receipt("eip155:8453", Some("3601"))), + }) + .unwrap(); + let latest = ledger::with_ledger(|ledger| ledger.payment(id).cloned().unwrap()).unwrap(); + assert_eq!(latest.status, PaymentStatus::Pending); + + runtime + .record(X402RecordPaymentRequest { + service: handle.clone(), + payment_id: id.to_string(), + response_status: 200, + settlement_response: Some(receipt("eip155:8453", Some(&charged.to_string()))), + }) + .unwrap(); + let latest = ledger::with_ledger(|ledger| ledger.payment(id).cloned().unwrap()).unwrap(); + assert_eq!(latest.status, PaymentStatus::Settled); + assert_eq!(latest.amount_atomic, charged); + assert_eq!( + latest.amount_display, + tinywallet_x402::ledger::format_usdc(charged) + ); + assert_eq!(latest.scheme.as_deref(), Some("upto")); + } + let summary = runtime.summary(&handle).unwrap(); + assert_eq!(summary.reserved_atomic, 0, "the unused ceiling is released"); + assert_eq!(summary.daily_total_atomic, 1200); + runtime.close(&handle).unwrap(); + broker_task.abort(); +} + +/// A runtime with one pending `upto` payment of 3600 under `id`. +async fn upto_runtime( + id: &str, +) -> ( + X402Runtime, + tokio::task::JoinHandle>, + tinybus::Connection, + tempfile::TempDir, +) { + let bus = tinybus::transport::memory::MemoryBus::new(); + let broker_task = tinybus::broker::Broker::new().spawn(bus.clone()); + let connection = tinybus::Connection::connect(bus.connect().await.unwrap()) + .await + .unwrap(); + let workspace = tempfile::tempdir().unwrap(); + let runtime = X402Runtime::new( + HostCallbacks::new(&connection).unwrap(), + X402ConfigResponse { + workspace_dir: workspace.path().display().to_string(), + session_id: "coverage-test".to_string(), + per_request_max_atomic: 10_000, + daily_max_atomic: 10_000, + monthly_max_atomic: 10_000, + }, + memory_ledger_storage(), + ) + .unwrap(); + let mut pending = pending_record(id, None); + pending.amount_atomic = 3600; + pending.network = "eip155:8453".to_string(); + pending.scheme = Some("upto".to_string()); + ledger::with_ledger_mut(|ledger| ledger.try_record_payment(pending)) + .unwrap() + .unwrap(); + (runtime, broker_task, connection, workspace) +} + +fn record_charge(runtime: &X402Runtime, id: &str, charged: Option<&str>) -> Result<(), String> { + runtime.record(X402RecordPaymentRequest { + service: runtime.handle(), + payment_id: id.to_string(), + response_status: 200, + settlement_response: charged.map(|amount| receipt("eip155:8453", Some(amount))), + }) +} + +fn charged(id: &str) -> (PaymentStatus, u64) { + ledger::with_ledger(|ledger| { + let latest = ledger.payment(id).unwrap(); + (latest.status, latest.amount_atomic) + }) + .unwrap() +} + +#[tokio::test] +async fn a_settled_payment_accepts_only_a_replay_of_the_same_charge() { + let _ledger_guard = LEDGER_TEST_LOCK.lock().await; + let (mut runtime, broker_task, _connection, _workspace) = upto_runtime("once").await; + + record_charge(&runtime, "once", Some("1200")).unwrap(); + assert_eq!(charged("once"), (PaymentStatus::Settled, 1200)); + + let error = record_charge(&runtime, "once", Some("1000")).unwrap_err(); + assert!(error.contains("already settled"), "{error}"); + assert_eq!(charged("once"), (PaymentStatus::Settled, 1200)); + + record_charge(&runtime, "once", Some("1200")).unwrap(); + record_charge(&runtime, "once", None).unwrap(); + let rows = ledger::with_ledger(|ledger| { + ledger + .recent_payments(50) + .into_iter() + .filter(|row| row.id == "once") + .count() + }) + .unwrap(); + assert_eq!(rows, 2, "one pending row and one settled row, no more"); + + let handle = runtime.handle(); + runtime.close(&handle).unwrap(); + broker_task.abort(); +} + +#[tokio::test] +async fn concurrent_receipts_settle_a_payment_once() { + let _ledger_guard = LEDGER_TEST_LOCK.lock().await; + let (mut runtime, broker_task, _connection, _workspace) = upto_runtime("raced").await; + + let outcomes = std::thread::scope(|scope| { + let first = scope.spawn(|| record_charge(&runtime, "raced", Some("1200"))); + let second = scope.spawn(|| record_charge(&runtime, "raced", Some("900"))); + [first.join().unwrap(), second.join().unwrap()] + }); + + assert_eq!(outcomes.iter().filter(|outcome| outcome.is_ok()).count(), 1); + let (status, amount) = charged("raced"); + assert_eq!(status, PaymentStatus::Settled); + let winner = if outcomes[0].is_ok() { 1200 } else { 900 }; + assert_eq!(amount, winner, "the ledger keeps the receipt that won"); + + let handle = runtime.handle(); + runtime.close(&handle).unwrap(); + broker_task.abort(); +} diff --git a/crates/tinywallet-module/src/service/x402_sign_in_tests.rs b/crates/tinywallet-module/src/service/x402_sign_in_tests.rs new file mode 100644 index 00000000..7a90843c --- /dev/null +++ b/crates/tinywallet-module/src/service/x402_sign_in_tests.rs @@ -0,0 +1,149 @@ +//! Tests for `X402SignIn`: the module signs a `sign-in-with-x` challenge with +//! the EVM secret it is handed, and refuses anything else. + +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use super::*; +use crate::service::x402::tests::secret; + +use base64::Engine as _; +use base64::engine::general_purpose::STANDARD as BASE64; +use tinywallet_bus::wire::X402SignInRequest; + +const URL: &str = "https://wallet.fixture.test/api/x-accounts/start"; + +/// A live-shaped challenge for the fixture origin, valid for five minutes. +fn challenge(domain: &str) -> String { + let now = chrono::Utc::now(); + BASE64.encode( + serde_json::to_vec(&serde_json::json!({ + "x402Version": 2, + "error": "SIWX authentication required", + "resource": {"url": URL}, + "accepts": [], + "extensions": {"sign-in-with-x": { + "info": { + "domain": domain, + "uri": URL, + "version": "1", + "nonce": "c3dae5e13c973fa183371bf7fa769206", + "issuedAt": now.to_rfc3339_opts(chrono::SecondsFormat::Millis, true), + "expirationTime": (now + chrono::Duration::minutes(5)) + .to_rfc3339_opts(chrono::SecondsFormat::Millis, true), + "statement": "Sign in to connect an account", + "resources": [URL] + }, + "supportedChains": [{"chainId": "eip155:8453", "type": "eip191"}] + }} + })) + .unwrap(), + ) +} + +fn request(payment_required: String, chain: tinywallet_bus::Chain) -> X402SignInRequest { + X402SignInRequest { + url: URL.to_string(), + payment_required, + secret: secret(chain), + } +} + +#[tokio::test] +async fn the_evm_account_signs_a_challenge_for_the_requested_host() { + let response = sign_in(request( + challenge("wallet.fixture.test"), + tinywallet_bus::Chain::Evm, + )) + .await + .unwrap(); + assert_eq!( + response.address, + "0x9858EfFD232B4033E47d90003D41EC34EcaEda94" + ); + assert_eq!(response.chain_id, "eip155:8453"); + let payload: serde_json::Value = + serde_json::from_slice(&BASE64.decode(&response.header).unwrap()).unwrap(); + assert_eq!(payload["address"], response.address); + assert_eq!(payload["domain"], "wallet.fixture.test"); + assert_eq!(payload["type"], "eip191"); + // `0x` + r ‖ s ‖ v. + assert_eq!(payload["signature"].as_str().unwrap().len(), 132); +} + +#[tokio::test] +async fn a_challenge_for_another_host_is_refused() { + let error = sign_in(request( + challenge("evil.example"), + tinywallet_bus::Chain::Evm, + )) + .await + .unwrap_err(); + assert!(error.contains("sign-in-with-x refused"), "{error}"); +} + +#[tokio::test] +async fn only_an_evm_secret_signs_in() { + let error = sign_in(request( + challenge("wallet.fixture.test"), + tinywallet_bus::Chain::Solana, + )) + .await + .unwrap_err(); + assert!(error.contains("EVM"), "{error}"); +} + +#[tokio::test] +async fn an_unreadable_challenge_is_refused() { + let error = sign_in(request("not base64!".into(), tinywallet_bus::Chain::Evm)) + .await + .unwrap_err(); + assert!(error.contains("challenge"), "{error}"); +} + +#[tokio::test] +async fn the_wallet_service_answers_x402_sign_in() { + let wallet = crate::service::Wallet::default(); + let response = wallet + .x402_sign_in(request( + challenge("wallet.fixture.test"), + tinywallet_bus::Chain::Evm, + )) + .await + .unwrap(); + assert_eq!(response.chain_id, "eip155:8453"); + + let error = wallet + .x402_sign_in(request( + challenge("evil.example"), + tinywallet_bus::Chain::Evm, + )) + .await + .unwrap_err(); + assert!( + format!("{error:?}").contains("sign-in-with-x refused"), + "{error:?}" + ); +} + +#[tokio::test] +async fn preparing_a_payment_before_x402_is_configured_is_refused() { + let wallet = crate::service::Wallet::default(); + let error = wallet + .x402_prepare_payment(tinywallet_bus::wire::X402PreparePaymentRequest { + service: tinywallet_bus::wire::X402ServiceHandle { + handle: "none".into(), + }, + url: URL.into(), + payment_required: challenge("wallet.fixture.test"), + owner: None, + secret: secret(tinywallet_bus::Chain::Evm), + additional_secrets: vec![secret(tinywallet_bus::Chain::Solana)], + network: None, + }) + .await + .unwrap_err(); + assert!( + format!("{error:?}").contains("HostUnavailable"), + "{error:?}" + ); +} diff --git a/crates/tinywallet-module/src/service/x402_tests.rs b/crates/tinywallet-module/src/service/x402_tests.rs index 5cae60b5..4ae7937f 100644 --- a/crates/tinywallet-module/src/service/x402_tests.rs +++ b/crates/tinywallet-module/src/service/x402_tests.rs @@ -33,6 +33,7 @@ pub(crate) fn pending_record( authorization_expiry_observed_height: None, session_id: "coverage-test".to_string(), thread_id: None, + scheme: None, } } @@ -150,6 +151,7 @@ async fn ledger_lifecycle_rejects_stale_handles_and_malformed_challenges() { payment_required: "unused".to_string(), owner: None, secret: secret(tinywallet_bus::Chain::Evm), + network: None, additional_secrets: vec![secret(tinywallet_bus::Chain::Evm)], }) .await @@ -167,6 +169,7 @@ async fn ledger_lifecycle_rejects_stale_handles_and_malformed_challenges() { owner: None, additional_secrets: Vec::new(), secret: secret(tinywallet_bus::Chain::Evm), + network: None, }) .await .unwrap_err(); @@ -180,6 +183,7 @@ async fn ledger_lifecycle_rejects_stale_handles_and_malformed_challenges() { owner: None, additional_secrets: Vec::new(), secret: secret(tinywallet_bus::Chain::Evm), + network: None, }) .await .unwrap_err(); @@ -502,6 +506,9 @@ impl PaymentApprovalHost { "getBlockHeight" => { serde_json::json!(self.finalized_height.load(Ordering::SeqCst)) } + // Every view call (an ERC-20 allowance, an EIP-2612 nonce) + // answers zero. + "eth_call" => serde_json::json!(format!("0x{}", "0".repeat(64))), _ => serde_json::Value::Null, } } @@ -645,6 +652,7 @@ async fn x402_pending_capacity_is_reserved_before_authorization_and_released_on_ }), additional_secrets: Vec::new(), secret: secret(tinywallet_bus::Chain::Evm), + network: None, }; for _ in 0..(MAX_PENDING - 1) { wallet.x402_prepare_payment(prepare()).await.unwrap(); @@ -723,6 +731,7 @@ async fn assert_admission_is_held_through_durable_commit( owner: None, additional_secrets: Vec::new(), secret: secret(tinywallet_bus::Chain::Evm), + network: None, }; let commit_reached = Arc::new(tokio::sync::Notify::new()); let release_commit = Arc::new(tokio::sync::Notify::new()); diff --git a/crates/tinywallet-module/tests/lifecycle_e2e.rs b/crates/tinywallet-module/tests/lifecycle_e2e.rs index 8745ffa6..6c46f6f3 100644 --- a/crates/tinywallet-module/tests/lifecycle_e2e.rs +++ b/crates/tinywallet-module/tests/lifecycle_e2e.rs @@ -96,6 +96,7 @@ const EXPECTED_METHODS: &[&str] = &[ "X402UpdateBudget", "X402Configure", "X402Close", + "X402SignIn", ]; /// The BIP-39 test vector mnemonic. Never use it for real funds. diff --git a/crates/tinywallet-module/tests/module_e2e.rs b/crates/tinywallet-module/tests/module_e2e.rs index 37892958..cbf7386b 100644 --- a/crates/tinywallet-module/tests/module_e2e.rs +++ b/crates/tinywallet-module/tests/module_e2e.rs @@ -75,6 +75,7 @@ const EXPECTED_METHODS: &[&str] = &[ "X402UpdateBudget", "X402Configure", "X402Close", + "X402SignIn", ]; /// The BIP-39 test vector mnemonic. Never use it for real funds. diff --git a/crates/tinywallet-x402/README.md b/crates/tinywallet-x402/README.md index 7d3edf2d..4e545c50 100644 --- a/crates/tinywallet-x402/README.md +++ b/crates/tinywallet-x402/README.md @@ -71,6 +71,35 @@ migration; it opens only after receiving that host-provisioned storage handle. (`Option`, omitted from the file when absent, so older ledgers still load) is the host's `ThreadScope::current_thread()`, for attribution. +## Schemes + +- **`exact`** on Solana (partially-signed SPL transfer) and EVM (EIP-3009). +- **`upto`** on EVM: a Permit2 `PermitWitnessTransferFrom` with the + `x402UptoPermit2Proxy` as spender and the `(to, facilitator, validAfter)` + witness. Selectable only with `extra.facilitatorAddress` and a Permit2 (or + absent) `extra.assetTransferMethod`; anything else is refused. Selection + prefers Solana `exact`, then EVM `exact`, then EVM `upto`. When the challenge + declares `eip2612GasSponsoring` and the payer's Permit2 allowance (read with + `eth_call` through the `Transport`) does not cover the amount, an EIP-2612 + `Permit` for Permit2 is signed for exactly `permitted.amount` (the proxy + requires that) and merged into `extensions`, as the reference client does. +- **Budget for `upto`.** The reservation, the host authorization and the + pending record use the signed ceiling. The receipt's `amount` (`settled_amount`) + is what a settled record keeps, from zero up to the ceiling; the rest of the + hold is released. `PaymentRecord.scheme` (and the stored row's `scheme`) + records which rule applies; absent means `exact`, whose receipt must name the + signed amount or none. +- **Network pin.** `handle_402_and_pay_on_network` takes a CAIP-2 chain id + (`eip155:8453`) or namespace (`eip155`, `solana`) and considers only those + options (`NoPaymentOptionOnNetwork` otherwise). +- **`sign-in-with-x`.** `crypto::sign_in_with_x` signs the EIP-4361 message + of a `sign-in-with-x` challenge with EIP-191, only for the requested host + (domain, HTTPS uri and resources on the requested origin, an expiry ahead, + single-line fields), and returns the `SIGN-IN-WITH-X` header value. +- **Echoed requirements.** `PaymentRequirements::other` and + `PaymentExtra::other` keep fields this crate does not model, so `accepted` + matches what a v2 server advertised. + ## Changes in 0.6.1 / 0.7.0 (API) - `X402PaymentResult` gains `reservation` and is no longer `Clone`, `PartialEq` or diff --git a/crates/tinywallet-x402/src/abi/mod.rs b/crates/tinywallet-x402/src/abi/mod.rs index 718d9352..32667dc9 100644 --- a/crates/tinywallet-x402/src/abi/mod.rs +++ b/crates/tinywallet-x402/src/abi/mod.rs @@ -14,6 +14,10 @@ use crate::eip712::u256_from_decimal; +mod reads; + +pub use reads::{decode_uint256, encode_eip2612_nonces, encode_erc20_allowance}; + /// `keccak256("transfer(address,uint256)")[..4]`. /// /// Pinned, and re-derived from the signature in the tests below. Every ERC-20 @@ -43,6 +47,13 @@ pub enum Error { /// What was wrong with it. reason: String, }, + + /// A contract call's reply is not the single word it should return. + #[error("invalid call reply: {reason}")] + InvalidReply { + /// What was wrong with it. + reason: String, + }, } /// Result alias for this module. diff --git a/crates/tinywallet-x402/src/abi/reads.rs b/crates/tinywallet-x402/src/abi/reads.rs new file mode 100644 index 00000000..1881f80f --- /dev/null +++ b/crates/tinywallet-x402/src/abi/reads.rs @@ -0,0 +1,80 @@ +//! The two read-only calls the x402 `upto` flow makes before it signs: the +//! payer's ERC-20 `allowance` to Permit2, and the token's EIP-2612 `nonces`. +//! +//! Both take only static arguments, so each is a selector followed by +//! left-padded address words, and each answers one `uint256` word. + +use super::{Error, Result, decode_evm_address, left_pad_address, push_hex}; +use crate::eip712::U256Bytes; + +/// `keccak256("allowance(address,address)")[..4]`. +pub(super) const ALLOWANCE_SELECTOR: [u8; 4] = [0xdd, 0x62, 0xed, 0x3e]; + +/// `keccak256("nonces(address)")[..4]`. +pub(super) const NONCES_SELECTOR: [u8; 4] = [0x7e, 0xce, 0xbe, 0x00]; + +/// ABI-encode an ERC-20 `allowance(owner, spender)` call, as `0x` hex. +/// +/// # Errors +/// +/// [`Error::InvalidRecipient`] when either address is not a valid EVM address. +pub fn encode_erc20_allowance(owner: &str, spender: &str) -> Result { + encode_call(ALLOWANCE_SELECTOR, &[owner, spender]) +} + +/// ABI-encode an EIP-2612 `nonces(owner)` call, as `0x` hex. +/// +/// # Errors +/// +/// [`Error::InvalidRecipient`] when `owner` is not a valid EVM address. +pub fn encode_eip2612_nonces(owner: &str) -> Result { + encode_call(NONCES_SELECTOR, &[owner]) +} + +/// Decode an `eth_call` reply that is exactly one `uint256` word. +/// +/// # Errors +/// +/// [`Error::InvalidReply`] when the reply is not `0x` plus 64 hex digits. +pub fn decode_uint256(reply: &str) -> Result { + let invalid = |reason: &str| Error::InvalidReply { + reason: reason.to_string(), + }; + let body = reply + .strip_prefix("0x") + .ok_or_else(|| invalid("missing 0x prefix"))?; + if body.len() != 64 { + return Err(invalid("expected one 32-byte word")); + } + let mut out = [0u8; 32]; + for (index, slot) in out.iter_mut().enumerate() { + *slot = body + .get(index * 2..index * 2 + 2) + .and_then(|pair| u8::from_str_radix(pair, 16).ok()) + .ok_or_else(|| invalid("not hex"))?; + } + Ok(out) +} + +fn encode_call(selector: [u8; 4], addresses: &[&str]) -> Result { + let mut out = String::with_capacity(2 + 8 + 64 * addresses.len()); + out.push_str("0x"); + for byte in selector { + push_hex(&mut out, byte); + } + for address in addresses { + let validated = tinywallet_crypto::address::evm::validate(address).map_err(|e| { + Error::InvalidRecipient { + reason: e.to_string(), + } + })?; + for byte in left_pad_address(decode_evm_address(&validated)?) { + push_hex(&mut out, byte); + } + } + Ok(out) +} + +#[cfg(test)] +#[path = "reads_tests.rs"] +mod tests; diff --git a/crates/tinywallet-x402/src/abi/reads_tests.rs b/crates/tinywallet-x402/src/abi/reads_tests.rs new file mode 100644 index 00000000..7d734171 --- /dev/null +++ b/crates/tinywallet-x402/src/abi/reads_tests.rs @@ -0,0 +1,70 @@ +//! Tests for the read-only ERC-20 / EIP-2612 calls the `upto` flow makes: +//! `allowance(owner, spender)` and `nonces(owner)`, and their `uint256` reply. + +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use super::super::keccak; +use super::*; + +const OWNER: &str = "0x9858EfFD232B4033E47d90003D41EC34EcaEda94"; +const PERMIT2: &str = "0x000000000022D473030F116dDEE9F6B43aC78BA3"; + +#[test] +fn the_pinned_selectors_match_their_signatures() { + assert_eq!( + keccak(b"allowance(address,address)")[..4], + ALLOWANCE_SELECTOR + ); + assert_eq!(keccak(b"nonces(address)")[..4], NONCES_SELECTOR); +} + +#[test] +fn allowance_calldata_is_the_selector_and_two_address_words() { + assert_eq!( + encode_erc20_allowance(OWNER, PERMIT2).unwrap(), + "0xdd62ed3e\ + 0000000000000000000000009858effd232b4033e47d90003d41ec34ecaeda94\ + 000000000000000000000000000000000022d473030f116ddee9f6b43ac78ba3" + ); +} + +#[test] +fn nonces_calldata_is_the_selector_and_one_address_word() { + assert_eq!( + encode_eip2612_nonces(OWNER).unwrap(), + "0x7ecebe00\ + 0000000000000000000000009858effd232b4033e47d90003d41ec34ecaeda94" + ); +} + +#[test] +fn a_bad_address_is_refused() { + assert!(matches!( + encode_eip2612_nonces("0x1234"), + Err(Error::InvalidRecipient { .. }) + )); + assert!(encode_erc20_allowance(OWNER, "nope").is_err()); +} + +#[test] +fn a_uint256_reply_decodes_to_its_big_endian_word() { + let word = decode_uint256("0x0000000000000000000000000000000000000000000000000000000000000e10") + .unwrap(); + assert_eq!(word[30..], [0x0e, 0x10]); + assert!(word[..30].iter().all(|b| *b == 0)); +} + +#[test] +fn a_reply_that_is_not_one_word_is_refused() { + for reply in [ + "0x", + "0x00", + "", + "0xzz00000000000000000000000000000000000000000000000000000000000000", + ] { + assert!( + matches!(decode_uint256(reply), Err(Error::InvalidReply { .. })), + "{reply}" + ); + } +} diff --git a/crates/tinywallet-x402/src/crypto/evm_payment.rs b/crates/tinywallet-x402/src/crypto/evm_payment.rs index 031195b9..a2a15970 100644 --- a/crates/tinywallet-x402/src/crypto/evm_payment.rs +++ b/crates/tinywallet-x402/src/crypto/evm_payment.rs @@ -16,7 +16,7 @@ use crate::wire::{ /// The longest an EIP-3009 authorization stays valid, whatever /// `maxTimeoutSeconds` the server asks for: an unbounded value would sign a /// transfer that never expires. -const MAX_AUTHORIZATION_SECS: u64 = 300; +pub(super) const MAX_AUTHORIZATION_SECS: u64 = 300; /// Build an EVM payment using EIP-3009 `transferWithAuthorization`. /// @@ -181,7 +181,7 @@ pub(super) fn evm_payment_payload( } /// The 20 raw bytes of an EVM address. -fn evm_address_bytes(address: &str) -> Result<[u8; 20], X402Error> { +pub(super) fn evm_address_bytes(address: &str) -> Result<[u8; 20], X402Error> { let validated = tinywallet_crypto::address::evm::validate(address) .map_err(|e| X402Error::Protocol(format!("invalid EVM address '{address}': {e}")))?; // `validate` guarantees 40 hex digits, so the decode cannot fail; one arm diff --git a/crates/tinywallet-x402/src/crypto/mod.rs b/crates/tinywallet-x402/src/crypto/mod.rs index 07da4e93..a73a355a 100644 --- a/crates/tinywallet-x402/src/crypto/mod.rs +++ b/crates/tinywallet-x402/src/crypto/mod.rs @@ -22,10 +22,13 @@ mod evm_payment; mod payments; mod signer; +mod siwx; mod solana_payment; +mod upto_payment; pub use payments::CryptoPayments; pub use signer::{PaymentAccount, PaymentSigner, SignScheme}; +pub use siwx::{SiwxProof, sign_in_with_x}; use sha2::{Digest, Sha256}; use std::sync::atomic::{AtomicU64, Ordering}; diff --git a/crates/tinywallet-x402/src/crypto/mod_tests.rs b/crates/tinywallet-x402/src/crypto/mod_tests.rs index 7afa604d..ced92e2e 100644 --- a/crates/tinywallet-x402/src/crypto/mod_tests.rs +++ b/crates/tinywallet-x402/src/crypto/mod_tests.rs @@ -64,14 +64,14 @@ async fn build_solana( fn evm_proof(payload: PaymentPayload) -> crate::wire::EvmPaymentProof { match payload.payload { PaymentProof::Evm(proof) => proof, - PaymentProof::Solana(_) => panic!("expected an EVM proof"), + other => panic!("expected an EVM proof, got {other:?}"), } } fn solana_transaction(payload: &PaymentPayload) -> Vec { match &payload.payload { PaymentProof::Solana(proof) => B64.decode(&proof.transaction).unwrap(), - PaymentProof::Evm(_) => panic!("expected a Solana proof"), + other => panic!("expected a Solana proof, got {other:?}"), } } @@ -216,6 +216,9 @@ async fn the_token_domain_defaults_to_usd_coin_version_two() { memo: None, name: Some("Other Coin".into()), version: Some("9".into()), + asset_transfer_method: None, + facilitator_address: None, + other: serde_json::Map::new(), }); let mut bare = evm_requirement(); bare.extra = None; diff --git a/crates/tinywallet-x402/src/crypto/payments.rs b/crates/tinywallet-x402/src/crypto/payments.rs index 86dce109..5098fc5d 100644 --- a/crates/tinywallet-x402/src/crypto/payments.rs +++ b/crates/tinywallet-x402/src/crypto/payments.rs @@ -9,10 +9,9 @@ use tinywallet_crypto::rpc::{self, NetworkId, Transport}; use super::evm_payment::build_evm_payment; use super::signer::PaymentSigner; use super::solana_payment::{b58_to_32, build_solana_payment}; +use super::upto_payment::build_upto_payment; use crate::protocol::{PaymentBuild, PaymentBuilder, X402Error}; -use crate::wire::{ - PaymentChain, PaymentPayload, PaymentProof, PaymentRequired, PaymentRequirements, -}; +use crate::wire::{PaymentChain, PaymentPayload, PaymentRequired, PaymentRequirements}; /// Builds EVM and Solana payments with an injected wallet and chain transport. #[derive(Clone)] @@ -61,20 +60,25 @@ impl CryptoPayments { .await?; (payload, Some(last_valid_height)) } + PaymentChain::Evm if requirement.scheme == "upto" => ( + build_upto_payment( + self.signer.as_ref(), + self.transport.as_ref(), + challenge, + requirement, + ) + .await?, + None, + ), PaymentChain::Evm => ( build_evm_payment(self.signer.as_ref(), challenge, requirement).await?, None, ), }; - let authorization_valid_until = match &payload.payload { - PaymentProof::Evm(proof) => proof - .authorization - .valid_before - .parse::() - .ok() - .and_then(|seconds| chrono::DateTime::from_timestamp(seconds, 0)), - PaymentProof::Solana(_) => None, - }; + let authorization_valid_until = payload + .payload + .authorization_deadline_secs() + .and_then(|seconds| chrono::DateTime::from_timestamp(seconds, 0)); Ok(PaymentBuild { payload, authorization_valid_until, diff --git a/crates/tinywallet-x402/src/crypto/siwx.rs b/crates/tinywallet-x402/src/crypto/siwx.rs new file mode 100644 index 00000000..7003037e --- /dev/null +++ b/crates/tinywallet-x402/src/crypto/siwx.rs @@ -0,0 +1,308 @@ +//! The x402 `sign-in-with-x` extension on EVM: an EIP-4361 (SIWE) message +//! built from the server's challenge, signed with EIP-191 `personal_sign` by +//! the wallet's EVM key. +//! +//! This signs a *sign-in*, not arbitrary text. Every line of the message comes +//! from the challenge and is checked first: the domain must be the requested +//! host, the URI and every resource must be HTTPS on the requested origin, +//! the message must carry an expiry still in the future and no field may +//! carry a line break that would forge another line of the message. A +//! challenge that fails any of these is refused before the wallet is asked. +//! +//! The message text matches the reference client's `formatSIWEMessage` (the +//! `@signinwithethereum/siwe` library's `prepareMessage`) byte for byte, and +//! the header is its `encodeSIWxHeader`: standard base64 of the JSON payload. + +use base64::Engine as _; +use base64::engine::general_purpose::STANDARD as B64; +use chrono::{DateTime, Duration, Utc}; +use log::debug; +use sha3::{Digest, Keccak256}; + +use super::LOG_PREFIX; +use super::evm_payment::eip712_signature; +use super::signer::{PaymentSigner, SignScheme}; +use crate::protocol::X402Error; +use crate::wire::{ + PaymentChain, PaymentRequired, SIGN_IN_WITH_X, SiwxExtension, SiwxInfo, SiwxPayload, +}; + +/// The chain preferred when the server accepts several: Base mainnet. +const PREFERRED_CHAIN_ID: u64 = 8453; + +/// How far ahead of this clock a server's `issuedAt` may be. +const MAX_CLOCK_SKEW_SECS: i64 = 300; + +/// The signed answer to a `sign-in-with-x` challenge. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct SiwxProof { + /// The `SIGN-IN-WITH-X` request header value. + pub header_value: String, + /// The account that signed in, EIP-55 checksummed. + pub address: String, + /// The CAIP-2 chain the sign-in names, such as `eip155:8453`. + pub chain_id: String, +} + +/// Sign the `sign-in-with-x` challenge in `challenge`, which answered a request +/// to `request_url`, with the wallet's EVM account. +/// +/// # Errors +/// +/// [`X402Error::SignInRefused`] when the challenge has no usable +/// `sign-in-with-x` extension or breaks one of the rules in the module docs; +/// nothing is signed then. [`X402Error::Wallet`] when the wallet cannot sign. +pub async fn sign_in_with_x( + signer: &dyn PaymentSigner, + challenge: &PaymentRequired, + request_url: &str, +) -> Result { + sign_in_with_x_at(signer, challenge, request_url, &Utc::now).await +} + +/// [`sign_in_with_x`] with the clock given. The clock is read before signing +/// and again after the wallet answers, so a challenge that expires while the +/// wallet is busy is not returned. +pub(super) async fn sign_in_with_x_at( + signer: &dyn PaymentSigner, + challenge: &PaymentRequired, + request_url: &str, + clock: &(dyn Fn() -> DateTime + Sync), +) -> Result { + let extension = challenge + .extensions + .get(SIGN_IN_WITH_X) + .ok_or_else(|| refused("the challenge does not ask for sign-in-with-x"))?; + let extension: SiwxExtension = serde_json::from_value(extension.clone()) + .map_err(|e| refused(&format!("unreadable sign-in-with-x extension: {e}")))?; + let info = extension.info; + // Before anything is parsed: URL parsing drops CR, LF and tab, so a value + // could pass the origin check yet forge an extra line of the message. + check_no_control_characters(&info, &extension.supported_chains)?; + check_origin(&info, request_url)?; + let expires_at = check_fields(&info, clock())?; + let chain_id = choose_chain(&extension.supported_chains)?; + + let account = signer + .account(PaymentChain::Evm) + .await + .map_err(X402Error::Wallet)?; + let address = tinywallet_crypto::address::evm::to_checksummed(&account.address) + .map_err(|e| X402Error::Wallet(format!("invalid wallet address: {e}")))?; + let message = siwe_message(&info, chain_id, &address); + let signature = signer + .sign( + PaymentChain::Evm, + &eip191_digest(&message), + SignScheme::Secp256k1Digest, + ) + .await + .map_err(|e| X402Error::Wallet(format!("sign sign-in-with-x: {e}")))?; + if expires_at <= clock() { + return Err(refused("the challenge expired while it was being signed")); + } + let signature = format!("0x{}", hex::encode(eip712_signature(&signature)?)); + + let chain_id = format!("eip155:{chain_id}"); + let payload = SiwxPayload { + domain: info.domain, + address: address.clone(), + statement: info.statement, + uri: info.uri, + version: info.version, + chain_id: chain_id.clone(), + kind: "eip191".to_string(), + nonce: info.nonce, + issued_at: info.issued_at, + expiration_time: info.expiration_time, + not_before: info.not_before, + request_id: info.request_id, + resources: info.resources, + signature, + }; + let json = serde_json::to_vec(&payload) + .map_err(|e| X402Error::Protocol(format!("serialize sign-in-with-x: {e}")))?; + debug!( + "{LOG_PREFIX} signed sign-in-with-x for {} on {chain_id}", + payload.domain + ); + Ok(SiwxProof { + header_value: B64.encode(json), + address, + chain_id, + }) +} + +/// The EIP-4361 message, laid out exactly as `SiweMessage.prepareMessage()`. +pub(super) fn siwe_message(info: &SiwxInfo, chain_id: u64, address: &str) -> String { + let mut lines = vec![ + format!("URI: {}", info.uri), + format!("Version: {}", info.version), + format!("Chain ID: {chain_id}"), + format!("Nonce: {}", info.nonce), + format!("Issued At: {}", info.issued_at), + ]; + if let Some(expiration) = &info.expiration_time { + lines.push(format!("Expiration Time: {expiration}")); + } + if let Some(not_before) = &info.not_before { + lines.push(format!("Not Before: {not_before}")); + } + if let Some(request_id) = &info.request_id { + lines.push(format!("Request ID: {request_id}")); + } + if let Some(resources) = &info.resources { + lines.push("Resources:".to_string()); + lines.extend(resources.iter().map(|resource| format!("- {resource}"))); + } + let header = format!( + "{} wants you to sign in with your Ethereum account:\n{address}", + info.domain + ); + let prefix = match &info.statement { + None => format!("{header}\n\n"), + Some(statement) => format!("{header}\n\n{statement}\n"), + }; + format!("{prefix}\n{}", lines.join("\n")) +} + +/// The EIP-191 `personal_sign` digest of `message`. +pub(super) fn eip191_digest(message: &str) -> [u8; 32] { + let mut hasher = Keccak256::new(); + hasher.update(format!("\x19Ethereum Signed Message:\n{}", message.len()).as_bytes()); + hasher.update(message.as_bytes()); + hasher.finalize().into() +} + +fn refused(reason: &str) -> X402Error { + X402Error::SignInRefused { + reason: reason.to_string(), + } +} + +/// The domain must be the requested host (and non-default port), and the URI +/// and every resource must be HTTPS on the requested origin. +fn check_origin(info: &SiwxInfo, request_url: &str) -> Result<(), X402Error> { + let request = + reqwest::Url::parse(request_url).map_err(|_| refused("the requested URL is not a URL"))?; + if request.scheme() != "https" { + return Err(refused("sign-in is only answered for an https request")); + } + let host = request.host_str().unwrap_or_default(); + let authority = match request.port() { + Some(port) => format!("{host}:{port}"), + None => host.to_string(), + }; + if info.domain != authority { + return Err(refused(&format!( + "domain {} is not the requested host {authority}", + info.domain + ))); + } + let same_origin = |uri: &str| { + reqwest::Url::parse(uri) + .is_ok_and(|url| url.scheme() == "https" && url.origin() == request.origin()) + }; + if !same_origin(&info.uri) { + return Err(refused(&format!( + "uri {} is not https on the requested origin", + info.uri + ))); + } + for resource in info.resources.iter().flatten() { + if !same_origin(resource) { + return Err(refused(&format!( + "resource {resource} is not https on the requested origin" + ))); + } + } + Ok(()) +} + +/// The fields that are copied into the message must be well formed: a known +/// version, an EIP-4361 nonce, RFC 3339 times, an expiry in the future, an +/// issue time not ahead of this clock, and no line breaks. +fn check_fields(info: &SiwxInfo, now: DateTime) -> Result, X402Error> { + if info.version != "1" { + return Err(refused(&format!("unsupported version {}", info.version))); + } + if info.nonce.len() < 8 || !info.nonce.bytes().all(|b| b.is_ascii_alphanumeric()) { + return Err(refused( + "the nonce is not at least 8 alphanumeric characters", + )); + } + let instant = |field: &str, value: &str| { + DateTime::parse_from_rfc3339(value) + .map(|at| at.with_timezone(&Utc)) + .map_err(|_| refused(&format!("{field} is not an RFC 3339 time"))) + }; + if instant("issuedAt", &info.issued_at)? > now + Duration::seconds(MAX_CLOCK_SKEW_SECS) { + return Err(refused("issuedAt is in the future")); + } + let expiration = info + .expiration_time + .as_deref() + .ok_or_else(|| refused("the challenge has no expirationTime"))?; + let expires_at = instant("expirationTime", expiration)?; + if expires_at <= now { + return Err(refused("the challenge has expired")); + } + if let Some(not_before) = &info.not_before { + instant("notBefore", not_before)?; + } + Ok(expires_at) +} + +/// Every value the message or the payload repeats must be free of control +/// characters: a line break would add a line of the server's choosing to +/// what the wallet signs. +fn check_no_control_characters( + info: &SiwxInfo, + chains: &[crate::wire::SiwxSupportedChain], +) -> Result<(), X402Error> { + let fields = [ + ("domain", Some(&info.domain)), + ("uri", Some(&info.uri)), + ("statement", info.statement.as_ref()), + ("version", Some(&info.version)), + ("nonce", Some(&info.nonce)), + ("issuedAt", Some(&info.issued_at)), + ("expirationTime", info.expiration_time.as_ref()), + ("notBefore", info.not_before.as_ref()), + ("requestId", info.request_id.as_ref()), + ]; + let resources = info + .resources + .iter() + .flatten() + .map(|r| ("resources", Some(r))); + let chain_ids = chains + .iter() + .map(|chain| ("chainId", Some(&chain.chain_id))); + for (field, value) in fields.into_iter().chain(resources).chain(chain_ids) { + if value.is_some_and(|text| text.chars().any(char::is_control)) { + return Err(refused(&format!("{field} contains a control character"))); + } + } + Ok(()) +} + +/// The EIP-155 chain id to sign for: an `eip155` chain with `eip191` +/// signatures, Base when offered. +fn choose_chain(chains: &[crate::wire::SiwxSupportedChain]) -> Result { + let candidates: Vec = chains + .iter() + .filter(|chain| chain.kind == "eip191") + .filter_map(|chain| chain.chain_id.strip_prefix("eip155:")?.parse().ok()) + .collect(); + candidates + .iter() + .copied() + .find(|id| *id == PREFERRED_CHAIN_ID) + .or_else(|| candidates.first().copied()) + .ok_or_else(|| refused("no eip155 chain with eip191 signatures is offered")) +} + +#[cfg(test)] +#[path = "siwx_tests.rs"] +mod tests; diff --git a/crates/tinywallet-x402/src/crypto/siwx_tests.rs b/crates/tinywallet-x402/src/crypto/siwx_tests.rs new file mode 100644 index 00000000..fa999d83 --- /dev/null +++ b/crates/tinywallet-x402/src/crypto/siwx_tests.rs @@ -0,0 +1,400 @@ +//! Tests for the `sign-in-with-x` proof: the EIP-4361 message, its EIP-191 +//! signature, the header, and every refusal. +//! +//! The expected messages and signatures were produced by the x402 reference +//! client's own libraries: `@signinwithethereum/siwe` `prepareMessage()` (what +//! the reference's `formatSIWEMessage` calls) and viem `signMessage` / +//! `hashMessage`, with the BIP-39 vector account. + +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use base64::engine::general_purpose::STANDARD as B64; +use chrono::{DateTime, Utc}; +use k256::ecdsa::{RecoveryId, Signature, SigningKey, VerifyingKey}; +use serde_json::{Value, json}; + +use super::*; +use crate::protocol::X402Error; +use crate::test_support::{EVM_ADDRESS, FakePaymentSigner}; +use crate::wire::{PaymentRequired, SiwxInfo}; + +const TWITR_SIWX: &str = include_str!("../wire/fixtures/twitr-siwx-challenge.json"); +const TWITR_URL: &str = "https://twitr.sh/api/x-accounts/start"; + +const SIWE_FULL: &str = "twitr.sh wants you to sign in with your Ethereum account:\n0x9858EfFD232B4033E47d90003D41EC34EcaEda94\n\nSign in to connect an account\n\nURI: https://twitr.sh/api/x-accounts/start\nVersion: 1\nChain ID: 8453\nNonce: c3dae5e13c973fa183371bf7fa769206\nIssued At: 2026-11-12T19:40:12.348Z\nExpiration Time: 2026-11-12T19:45:12.348Z\nResources:\n- https://twitr.sh/api/x-accounts/start"; +const SIWE_FULL_SIGNATURE: &str = "0xe1b40232340ee327925f48ff33c416ff59a03fc3938e769334ebfeed1bba39d87e8108ac7bf0cd35186fbfec0bcfcc3213fa44115b39ea65cd61abdc564668c91b"; +const SIWE_BARE: &str = "twitr.sh wants you to sign in with your Ethereum account:\n0x9858EfFD232B4033E47d90003D41EC34EcaEda94\n\n\nURI: https://twitr.sh/api/x-accounts/start\nVersion: 1\nChain ID: 84532\nNonce: abcdef0123456789\nIssued At: 2026-11-12T19:40:12.348Z\nNot Before: 2026-11-12T19:40:00.000Z\nRequest ID: req-1"; +const SIWE_BARE_DIGEST: &str = "c053a0ec57ae652fdf2b9dbeebcf598e4632366244a283b9cac23053f6b55e8b"; + +/// Inside the fixture's validity window. +fn now() -> DateTime { + "2026-11-12T19:41:00Z".parse().unwrap() +} + +fn twitr() -> PaymentRequired { + serde_json::from_str(TWITR_SIWX).unwrap() +} + +fn twitr_info() -> SiwxInfo { + serde_json::from_value(twitr().extensions["sign-in-with-x"]["info"].clone()).unwrap() +} + +/// `twitr()` with `edit` applied to its raw `sign-in-with-x` extension. +fn twitr_with(edit: impl FnOnce(&mut Value)) -> PaymentRequired { + let mut challenge = twitr(); + edit(challenge.extensions.get_mut("sign-in-with-x").unwrap()); + challenge +} + +fn recover(digest: [u8; 32], signature_hex: &str) -> VerifyingKey { + let bytes = hex::decode(signature_hex.trim_start_matches("0x")).unwrap(); + let signature = Signature::from_slice(&bytes[..64]).unwrap(); + let recovery = RecoveryId::from_byte(bytes[64] - 27).unwrap(); + VerifyingKey::recover_from_prehash(&digest, &signature, recovery).unwrap() +} + +async fn sign(challenge: &PaymentRequired, url: &str) -> Result { + sign_in_with_x_at(&FakePaymentSigner::default(), challenge, url, &now).await +} + +#[test] +fn the_message_is_the_reference_siwe_text() { + assert_eq!(siwe_message(&twitr_info(), 8453, EVM_ADDRESS), SIWE_FULL); +} + +#[test] +fn optional_fields_are_laid_out_as_the_reference_does() { + let mut info = twitr_info(); + info.statement = None; + info.nonce = "abcdef0123456789".into(); + info.expiration_time = None; + info.not_before = Some("2026-11-12T19:40:00.000Z".into()); + info.request_id = Some("req-1".into()); + info.resources = None; + let message = siwe_message(&info, 84532, EVM_ADDRESS); + assert_eq!(message, SIWE_BARE); + assert_eq!(hex::encode(eip191_digest(&message)), SIWE_BARE_DIGEST); +} + +#[tokio::test] +async fn the_twitr_challenge_is_signed_exactly_as_the_reference_client_signs_it() { + let signer = FakePaymentSigner::default(); + let proof = sign_in_with_x_at(&signer, &twitr(), TWITR_URL, &now) + .await + .unwrap(); + + assert_eq!(proof.address, EVM_ADDRESS); + assert_eq!(proof.chain_id, "eip155:8453"); + let payload: Value = serde_json::from_slice(&B64.decode(&proof.header_value).unwrap()).unwrap(); + assert_eq!( + payload, + json!({ + "domain": "twitr.sh", + "address": EVM_ADDRESS, + "statement": "Sign in to connect an account", + "uri": TWITR_URL, + "version": "1", + "chainId": "eip155:8453", + "type": "eip191", + "nonce": "c3dae5e13c973fa183371bf7fa769206", + "issuedAt": "2026-11-12T19:40:12.348Z", + "expirationTime": "2026-11-12T19:45:12.348Z", + "resources": [TWITR_URL], + "signature": SIWE_FULL_SIGNATURE + }) + ); + // Recovered independently of the reference: EIP-191 over the SIWE text. + assert_eq!( + recover(eip191_digest(SIWE_FULL), SIWE_FULL_SIGNATURE), + *SigningKey::from_slice(&FakePaymentSigner::evm_secret()) + .unwrap() + .verifying_key() + ); + assert_eq!(signer.sign_calls.lock().unwrap().len(), 1); +} + +#[tokio::test] +async fn base_is_preferred_whatever_order_the_server_lists_chains_in() { + let challenge = twitr_with(|siwx| { + siwx["supportedChains"] = json!([ + {"chainId": "solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp", "type": "ed25519"}, + {"chainId": "eip155:84532", "type": "eip191"}, + {"chainId": "eip155:8453", "type": "eip191"} + ]); + }); + assert_eq!( + sign(&challenge, TWITR_URL).await.unwrap().chain_id, + "eip155:8453" + ); + + let challenge = twitr_with(|siwx| { + siwx["supportedChains"] = json!([ + {"chainId": "solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp", "type": "ed25519"}, + {"chainId": "eip155:1", "type": "eip1271"}, + {"chainId": "eip155:84532", "type": "eip191"} + ]); + }); + assert_eq!( + sign(&challenge, TWITR_URL).await.unwrap().chain_id, + "eip155:84532" + ); +} + +/// Refusals for a challenge that is not for the requested origin, with the +/// URL it answered. +fn origin_refusals() -> Vec<(&'static str, PaymentRequired, &'static str)> { + vec![ + ( + "no extension", + { + let mut c = twitr(); + c.extensions.clear(); + c + }, + TWITR_URL, + ), + ( + "domain of another host", + twitr(), + "https://evil.example/api/x-accounts/start", + ), + ( + "plain http request", + twitr(), + "http://twitr.sh/api/x-accounts/start", + ), + ( + "domain mismatch", + twitr_with(|s| s["info"]["domain"] = "evil.example".into()), + TWITR_URL, + ), + ( + "uri on another host", + twitr_with(|s| s["info"]["uri"] = "https://evil.example/x".into()), + TWITR_URL, + ), + ( + "uri over http", + twitr_with(|s| s["info"]["uri"] = "http://twitr.sh/x".into()), + TWITR_URL, + ), + ( + "resource on another host", + twitr_with(|s| s["info"]["resources"] = json!(["https://evil.example/r"])), + TWITR_URL, + ), + ( + "resource not a URI", + twitr_with(|s| s["info"]["resources"] = json!(["not a uri"])), + TWITR_URL, + ), + ] +} + +/// Refusals for fields that are malformed, out of date, or could forge a line. +fn field_refusals() -> Vec<(&'static str, PaymentRequired, &'static str)> { + vec![ + ( + "expired", + twitr_with(|s| s["info"]["expirationTime"] = "2026-11-12T19:40:59Z".into()), + TWITR_URL, + ), + ( + "no expiry", + twitr_with(|s| { + s["info"].as_object_mut().unwrap().remove("expirationTime"); + }), + TWITR_URL, + ), + ( + "issued in the future", + twitr_with(|s| s["info"]["issuedAt"] = "2026-11-12T20:41:00Z".into()), + TWITR_URL, + ), + ( + "issuedAt not a date", + twitr_with(|s| s["info"]["issuedAt"] = "yesterday".into()), + TWITR_URL, + ), + ( + "notBefore not a date", + twitr_with(|s| s["info"]["notBefore"] = "soon\nURI: x".into()), + TWITR_URL, + ), + ( + "statement with a line break", + twitr_with(|s| s["info"]["statement"] = "hi\nURI: https://evil.example".into()), + TWITR_URL, + ), + ( + "requestId with a line break", + twitr_with(|s| s["info"]["requestId"] = "a\nb".into()), + TWITR_URL, + ), + ( + "short nonce", + twitr_with(|s| s["info"]["nonce"] = "abc".into()), + TWITR_URL, + ), + ( + "nonce with punctuation", + twitr_with(|s| s["info"]["nonce"] = "abcdefgh!".into()), + TWITR_URL, + ), + ( + "another version", + twitr_with(|s| s["info"]["version"] = "2".into()), + TWITR_URL, + ), + ( + "no EVM chain", + twitr_with(|s| { + s["supportedChains"] = json!([{"chainId": "solana:x", "type": "ed25519"}]); + }), + TWITR_URL, + ), + ( + "no eip191 chain", + twitr_with(|s| { + s["supportedChains"] = json!([{"chainId": "eip155:8453", "type": "eip1271"}]); + }), + TWITR_URL, + ), + ( + "malformed chain id", + twitr_with(|s| { + s["supportedChains"] = json!([{"chainId": "eip155:base", "type": "eip191"}]); + }), + TWITR_URL, + ), + ( + "not an object", + twitr_with(|s| *s = json!("sign me")), + TWITR_URL, + ), + ] +} + +#[tokio::test] +async fn a_challenge_outside_the_rules_is_refused_before_signing() { + for (case, challenge, url) in origin_refusals().into_iter().chain(field_refusals()) { + let signer = FakePaymentSigner::default(); + let error = sign_in_with_x_at(&signer, &challenge, url, &now) + .await + .unwrap_err(); + assert!( + matches!(error, X402Error::SignInRefused { .. }), + "{case}: {error}" + ); + assert!( + signer.sign_calls.lock().unwrap().is_empty(), + "{case}: signed" + ); + } +} + +#[tokio::test] +async fn a_wallet_failure_is_a_wallet_error() { + let signer = FakePaymentSigner { + sign_error: Some("locked".into()), + ..FakePaymentSigner::default() + }; + let error = sign_in_with_x_at(&signer, &twitr(), TWITR_URL, &now) + .await + .unwrap_err(); + assert_eq!( + error.to_string(), + "x402 wallet: sign sign-in-with-x: locked" + ); +} + +#[test] +fn the_refusal_message_is_pinned() { + assert_eq!( + X402Error::SignInRefused { + reason: "expired".into() + } + .to_string(), + "x402 sign-in-with-x refused: expired" + ); +} + +/// A value smuggling a line break (or another control character) into any +/// field the message repeats. +fn injection_refusals() -> Vec<(&'static str, PaymentRequired)> { + let field = |name: &'static str, value: &'static str| { + ( + name, + twitr_with(move |s| { + s["info"][name] = value.into(); + }), + ) + }; + vec![ + ( + "resource", + twitr_with(|s| { + s["info"]["resources"] = json!(["https://twitr.sh/r\n- https://evil.example/"]); + }), + ), + field( + "uri", + "https://twitr.sh/api/x-accounts/start\nURI: https://evil.example/", + ), + field("uri", "https://twitr.sh/api/x-accounts/start\r"), + field("domain", "twitr.sh\n"), + field("nonce", "c3dae5e13c973fa183\n71bf7fa769206"), + field("issuedAt", "2026-11-12T19:40:12.348Z\n"), + field("expirationTime", "2026-11-12T19:45:12.348Z\nNot Before: x"), + field("notBefore", "2026-11-12T19:40:00Z\n"), + field("statement", "hi\tthere"), + field("requestId", "a\u{0}b"), + field("version", "1\n"), + ( + "chainId", + twitr_with(|s| { + s["supportedChains"] = json!([{"chainId": "eip155:8453\n", "type": "eip191"}]); + }), + ), + ] +} + +#[tokio::test] +async fn a_control_character_in_any_signed_field_is_refused() { + for (field, challenge) in injection_refusals() { + let signer = FakePaymentSigner::default(); + let error = sign_in_with_x_at(&signer, &challenge, TWITR_URL, &now) + .await + .unwrap_err(); + assert!( + matches!(&error, X402Error::SignInRefused { reason } if reason.contains("control character") || reason.contains(field)), + "{field}: {error}" + ); + assert!( + signer.sign_calls.lock().unwrap().is_empty(), + "{field}: signed" + ); + } +} + +#[tokio::test] +async fn a_challenge_that_expires_while_the_wallet_signs_is_not_returned() { + let reads = std::sync::atomic::AtomicUsize::new(0); + // The first read is inside the window; every later one is past expiry. + let clock = || { + if reads.fetch_add(1, std::sync::atomic::Ordering::SeqCst) == 0 { + now() + } else { + "2026-11-12T19:46:00Z".parse().unwrap() + } + }; + let signer = FakePaymentSigner::default(); + let error = sign_in_with_x_at(&signer, &twitr(), TWITR_URL, &clock) + .await + .unwrap_err(); + assert_eq!( + error.to_string(), + "x402 sign-in-with-x refused: the challenge expired while it was being signed" + ); + assert_eq!(signer.sign_calls.lock().unwrap().len(), 1); +} diff --git a/crates/tinywallet-x402/src/crypto/upto_payment.rs b/crates/tinywallet-x402/src/crypto/upto_payment.rs new file mode 100644 index 00000000..3d6dcc33 --- /dev/null +++ b/crates/tinywallet-x402/src/crypto/upto_payment.rs @@ -0,0 +1,348 @@ +//! EVM `upto` scheme payment construction: a Permit2 +//! `PermitWitnessTransferFrom` whose spender is the `x402UptoPermit2Proxy`, +//! signed over its EIP-712 digest by the wallet's EVM key, plus the optional +//! EIP-2612 `Permit` the `eip2612GasSponsoring` extension asks for. +//! +//! The payer signs a ceiling (`permitted.amount`); the facilitator later +//! settles the amount actually used, which may be anything up to it. +//! +//! Matches the x402 reference client (`createUptoPermit2Payload` and +//! `trySignEip2612PermitExtension` in coinbase/x402), with one deliberate +//! difference: the deadline is capped at [`MAX_AUTHORIZATION_SECS`] as for an +//! EIP-3009 authorization, rather than taken from `maxTimeoutSeconds` as is. + +use log::debug; +use serde_json::{Map, Value, json}; +use tinywallet_crypto::rpc::{NetworkId, Transport}; + +use super::evm_payment::{MAX_AUTHORIZATION_SECS, eip712_signature, evm_address_bytes}; +use super::signer::{PaymentSigner, SignScheme}; +use super::{LOG_PREFIX, fresh_nonce}; +use crate::abi; +use crate::eip712::{self, U256Bytes, UptoPermit}; +use crate::protocol::X402Error; +use crate::wire::{ + EIP2612_GAS_SPONSORING, PERMIT2_ADDRESS, PaymentChain, PaymentPayload, PaymentProof, + PaymentRequired, PaymentRequirements, Permit2Authorization, Permit2PaymentProof, + TokenPermissions, UPTO_PERMIT2_PROXY_ADDRESS, UptoWitness, X402_VERSION, +}; + +/// The `eip2612GasSponsoring` info schema version the reference client sends. +const EIP2612_INFO_VERSION: &str = "1"; + +/// Build and sign an `upto` payment with a fresh nonce at the current time. +pub(super) async fn build_upto_payment( + signer: &dyn PaymentSigner, + transport: &dyn Transport, + challenge: &PaymentRequired, + requirement: &PaymentRequirements, +) -> Result { + let now = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap_or_default() + .as_secs(); + build_upto_payment_at( + signer, + transport, + challenge, + requirement, + fresh_nonce(), + now, + ) + .await +} + +/// [`build_upto_payment`] with the nonce and the clock given. +pub(super) async fn build_upto_payment_at( + signer: &dyn PaymentSigner, + transport: &dyn Transport, + challenge: &PaymentRequired, + requirement: &PaymentRequirements, + nonce: U256Bytes, + now_secs: u64, +) -> Result { + let account = signer + .account(PaymentChain::Evm) + .await + .map_err(X402Error::Wallet)?; + let terms = upto_terms(&account.address, requirement, nonce, now_secs)?; + let signature = sign_digest(signer, terms.digest(), "Permit2").await?; + + let mut client_extensions = Map::new(); + if let Some(info) = + eip2612_permit_info(signer, transport, challenge, requirement, &terms).await? + { + client_extensions.insert(EIP2612_GAS_SPONSORING.to_string(), json!({ "info": info })); + } + + debug!( + "{LOG_PREFIX} built EVM upto payment chain_id={} max_amount={} asset={} to={} sponsored_permit={}", + terms.chain_id, + requirement.amount, + requirement.asset, + requirement.pay_to, + !client_extensions.is_empty() + ); + + Ok(PaymentPayload { + x402_version: X402_VERSION, + resource: Some(challenge.resource.clone()), + accepted: requirement.clone(), + payload: PaymentProof::Permit2(Permit2PaymentProof { + signature, + permit2_authorization: terms.authorization(), + }), + extensions: merge_extensions(&challenge.extensions, client_extensions), + }) +} + +/// Everything an `upto` permit binds, in both its hashed and its wire form. +#[derive(Debug)] +pub(super) struct UptoTerms { + permit: UptoPermit, + chain_id: u64, + from: String, + token: String, + amount: String, + to: String, + facilitator: String, + nonce: String, + deadline_secs: u64, +} + +impl UptoTerms { + /// The 32-byte EIP-712 digest to sign, under Permit2's domain. + pub(super) fn digest(&self) -> [u8; 32] { + eip712::signing_digest( + eip712::permit2_domain_separator(self.chain_id), + self.permit.struct_hash(), + ) + } + + fn authorization(&self) -> Permit2Authorization { + Permit2Authorization { + from: self.from.clone(), + permitted: TokenPermissions { + token: self.token.clone(), + amount: self.amount.clone(), + }, + spender: UPTO_PERMIT2_PROXY_ADDRESS.to_string(), + nonce: self.nonce.clone(), + deadline: self.deadline_secs.to_string(), + witness: UptoWitness { + to: self.to.clone(), + facilitator: self.facilitator.clone(), + valid_after: "0".to_string(), + }, + } + } +} + +/// Read the permit terms out of `requirement`: valid from time zero, void +/// after `maxTimeoutSeconds` (capped), for at most `amount`. +pub(super) fn upto_terms( + from_address: &str, + requirement: &PaymentRequirements, + nonce: U256Bytes, + now_secs: u64, +) -> Result { + let chain_id = requirement.evm_chain_id().ok_or_else(|| { + X402Error::Protocol(format!("not an EVM network: {}", requirement.network)) + })?; + // `upto` allows Permit2 only; an absent method means Permit2. + if let Some(method) = requirement + .extra + .as_ref() + .and_then(|extra| extra.asset_transfer_method.as_deref()) + .filter(|method| *method != "permit2") + { + return Err(X402Error::Protocol(format!( + "upto requirement asks for assetTransferMethod {method}; only permit2 is supported" + ))); + } + let facilitator = requirement + .extra + .as_ref() + .and_then(|extra| extra.facilitator_address.as_deref()) + .ok_or_else(|| { + X402Error::Protocol("upto requirement has no extra.facilitatorAddress".to_string()) + })?; + let amount = eip712::u256_from_decimal(&requirement.amount).map_err(|e| { + X402Error::Protocol(format!("invalid amount '{}': {e}", requirement.amount)) + })?; + let deadline_secs = now_secs.saturating_add( + requirement + .max_timeout_seconds + .clamp(1, MAX_AUTHORIZATION_SECS), + ); + + let permit = UptoPermit { + token: evm_address_bytes(&requirement.asset)?, + amount, + spender: eip712::UPTO_PERMIT2_PROXY, + nonce, + deadline: eip712::u256_from_u64(deadline_secs), + to: evm_address_bytes(&requirement.pay_to)?, + facilitator: evm_address_bytes(facilitator)?, + valid_after: eip712::u256_from_u64(0), + }; + Ok(UptoTerms { + permit, + chain_id, + from: checksummed(from_address)?, + token: checksummed(&requirement.asset)?, + amount: requirement.amount.trim().to_string(), + to: checksummed(&requirement.pay_to)?, + facilitator: checksummed(facilitator)?, + nonce: eip712::u256_to_decimal(&nonce), + deadline_secs, + }) +} + +/// The `eip2612GasSponsoring` info, when the server sponsors it and the payer's +/// Permit2 allowance does not already cover the permit. `None` otherwise. +/// +/// As in the reference client: no token domain (`extra.name` and +/// `extra.version`) means no permit; an allowance that cannot be read is +/// treated as insufficient; a token nonce that cannot be read fails the +/// payment, because a permit over a guessed nonce is rejected on chain. The +/// permit approves exactly `permitted.amount`, which is what the proxy's +/// `settleWithPermit` requires, and shares the Permit2 deadline. +async fn eip2612_permit_info( + signer: &dyn PaymentSigner, + transport: &dyn Transport, + challenge: &PaymentRequired, + requirement: &PaymentRequirements, + terms: &UptoTerms, +) -> Result, X402Error> { + if !challenge.extensions.contains_key(EIP2612_GAS_SPONSORING) { + return Ok(None); + } + let extra = requirement.extra.as_ref(); + let (Some(name), Some(version)) = ( + extra.and_then(|extra| extra.name.as_deref()), + extra.and_then(|extra| extra.version.as_deref()), + ) else { + return Ok(None); + }; + let network = NetworkId::evm(terms.chain_id); + + let allowance_call = abi::encode_erc20_allowance(&terms.from, PERMIT2_ADDRESS) + .map_err(|e| X402Error::Protocol(format!("encode allowance call: {e}")))?; + match read_uint256(transport, network, &terms.token, &allowance_call).await { + Ok(allowance) if allowance >= terms.permit.amount => { + debug!("{LOG_PREFIX} Permit2 allowance covers the upto amount; no EIP-2612 permit"); + return Ok(None); + } + Ok(_) => {} + Err(error) => { + debug!( + "{LOG_PREFIX} Permit2 allowance unreadable ({error}); signing an EIP-2612 permit" + ); + } + } + + let nonce_call = abi::encode_eip2612_nonces(&terms.from) + .map_err(|e| X402Error::Protocol(format!("encode nonces call: {e}")))?; + let nonce = read_uint256(transport, network, &terms.token, &nonce_call) + .await + .map_err(|error| X402Error::Wallet(format!("read EIP-2612 nonce: {error}")))?; + + let permit = eip712::Eip2612Permit { + owner: evm_address_bytes(&terms.from)?, + spender: eip712::PERMIT2, + value: terms.permit.amount, + nonce, + deadline: terms.permit.deadline, + }; + let domain = eip712::domain_separator(terms.permit.token, terms.chain_id, name, version); + let digest = eip712::signing_digest(domain, permit.struct_hash()); + let signature = sign_digest(signer, digest, "EIP-2612").await?; + + Ok(Some(json!({ + "from": terms.from, + "asset": terms.token, + "spender": PERMIT2_ADDRESS, + "amount": terms.amount, + "nonce": eip712::u256_to_decimal(&nonce), + "deadline": terms.deadline_secs.to_string(), + "signature": signature, + "version": EIP2612_INFO_VERSION, + }))) +} + +/// `eth_call` a view function on `contract` that returns one `uint256`. +async fn read_uint256( + transport: &dyn Transport, + network: NetworkId, + contract: &str, + calldata: &str, +) -> Result { + let reply = transport + .json_rpc( + network, + "eth_call", + json!([{ "to": contract, "data": calldata }, "latest"]), + ) + .await + .map_err(|error| error.to_string())?; + let reply = reply + .as_str() + .ok_or_else(|| format!("eth_call returned a non-string result: {reply}"))?; + abi::decode_uint256(reply).map_err(|error| error.to_string()) +} + +/// Sign an EIP-712 digest behind the seam and return `0x` + `r ‖ s ‖ v`. +async fn sign_digest( + signer: &dyn PaymentSigner, + digest: [u8; 32], + what: &str, +) -> Result { + let signature = signer + .sign(PaymentChain::Evm, &digest, SignScheme::Secp256k1Digest) + .await + .map_err(|e| X402Error::Wallet(format!("sign {what}: {e}")))?; + Ok(format!("0x{}", hex::encode(eip712_signature(&signature)?))) +} + +/// The EIP-55 form of an address, as the reference client's `getAddress`. +fn checksummed(address: &str) -> Result { + tinywallet_crypto::address::evm::to_checksummed(address) + .map_err(|e| X402Error::Protocol(format!("invalid EVM address '{address}': {e}"))) +} + +/// The payload's `extensions`: the server's declarations with the client's +/// entries merged over them, objects recursively and anything else replaced, +/// as the reference client's `mergeExtensions` does. +fn merge_extensions(server: &Map, client: Map) -> Map { + let mut merged = server.clone(); + for (key, value) in client { + match merged.get_mut(&key) { + Some(existing) => merge_value(existing, value), + None => { + merged.insert(key, value); + } + } + } + merged +} + +fn merge_value(target: &mut Value, source: Value) { + match (target, source) { + (Value::Object(target), Value::Object(source)) => { + for (key, value) in source { + match target.get_mut(&key) { + Some(existing) => merge_value(existing, value), + None => { + target.insert(key, value); + } + } + } + } + (target, source) => *target = source, + } +} + +#[cfg(test)] +#[path = "upto_payment_tests.rs"] +mod tests; diff --git a/crates/tinywallet-x402/src/crypto/upto_payment_tests.rs b/crates/tinywallet-x402/src/crypto/upto_payment_tests.rs new file mode 100644 index 00000000..31b3926b --- /dev/null +++ b/crates/tinywallet-x402/src/crypto/upto_payment_tests.rs @@ -0,0 +1,461 @@ +//! Tests for the EVM `upto` payment: the Permit2 permit, its signature, and +//! the `eip2612GasSponsoring` extension. +//! +//! The expected digests and signatures were produced by the x402 reference +//! client's own libraries (viem `hashTypedData` / `signTypedData` over the +//! reference type definitions) with the BIP-39 vector account; see +//! `eip712/permit2_tests.rs`. k256 and viem both sign with RFC 6979, so the +//! whole signature, not only the signer, must match. + +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use k256::ecdsa::{RecoveryId, Signature, SigningKey, VerifyingKey}; +use serde_json::{Value, json}; +use tinywallet_crypto::rpc::{NetworkId, TransportError}; + +use super::*; +use crate::crypto::CryptoPayments; +use crate::eip712; +use crate::protocol::PaymentBuilder; +use crate::test_support::{EVM_ADDRESS, FakePaymentSigner, FakeTransport}; +use crate::wire::{PaymentProof, PaymentRequired}; + +const TWITR_UPTO: &str = include_str!("../wire/fixtures/twitr-upto-challenge.json"); +/// The Permit2 nonce of the reference vector. +const NONCE: &str = "33247007178036348590600198031289925668252061821958005840077069883511451257277"; +/// The deadline of the reference vector, reached with twitr's 300 s timeout. +const DEADLINE: u64 = 1_740_672_154; +const NOW: u64 = DEADLINE - 300; +const UPTO_SIGNATURE: &str = "0x9ab5dff608f9cde97db904773e2cca5188d24d47119bd64766bd80998e6750c453d5a9f9cdcd54a48bc189686de69d61d6a5b8a0922ff5520f8c0af5746015a21b"; +const PERMIT2_CALLDATA_TAIL: &str = + "000000000000000000000000000000000022d473030f116ddee9f6b43ac78ba3"; + +fn twitr() -> PaymentRequired { + serde_json::from_str(TWITR_UPTO).unwrap() +} + +fn word(value: u64) -> Value { + json!(format!("0x{value:064x}")) +} + +type TransportResult = tinywallet_crypto::rpc::TransportResult; + +fn transport(replies: Vec) -> FakeTransport { + let transport = FakeTransport::default(); + transport.responses.lock().unwrap().extend(replies); + transport +} + +async fn build( + challenge: &PaymentRequired, + transport: &FakeTransport, +) -> Result { + build_upto_payment_at( + &FakePaymentSigner::default(), + transport, + challenge, + &challenge.accepts[0], + eip712::u256_from_decimal(NONCE).unwrap(), + NOW, + ) + .await +} + +fn recover(digest: [u8; 32], signature_hex: &str) -> VerifyingKey { + let bytes = hex::decode(signature_hex.trim_start_matches("0x")).unwrap(); + let signature = Signature::from_slice(&bytes[..64]).unwrap(); + let recovery = RecoveryId::from_byte(bytes[64] - 27).unwrap(); + VerifyingKey::recover_from_prehash(&digest, &signature, recovery).unwrap() +} + +fn payer_key() -> VerifyingKey { + *SigningKey::from_slice(&FakePaymentSigner::evm_secret()) + .unwrap() + .verifying_key() +} + +fn permit2(payload: &PaymentPayload) -> &crate::wire::Permit2PaymentProof { + match &payload.payload { + PaymentProof::Permit2(proof) => proof, + other => panic!("expected a Permit2 proof, got {other:?}"), + } +} + +#[test] +fn the_terms_hash_to_the_reference_digest() { + let terms = upto_terms( + EVM_ADDRESS, + &twitr().accepts[0], + eip712::u256_from_decimal(NONCE).unwrap(), + NOW, + ) + .unwrap(); + assert_eq!( + hex::encode(terms.digest()), + "8e8c28bb23e744c0eb81bdfab664afc6c046d317a33873fdf0ffa275ecee94f9" + ); +} + +#[tokio::test] +async fn the_twitr_challenge_yields_the_reference_payload() { + // Allowance already covers the amount, so no permit is signed. + let transport = transport(vec![Ok(word(1_000_000))]); + let challenge = twitr(); + let payload = build(&challenge, &transport).await.unwrap(); + + assert_eq!(payload.x402_version, 2); + assert_eq!( + payload.resource.as_ref().unwrap().url, + challenge.resource.url + ); + assert_eq!( + serde_json::to_value(&payload.accepted).unwrap(), + serde_json::from_str::(TWITR_UPTO).unwrap()["accepts"][0], + "the server must find its own requirement in `accepted`" + ); + let proof = permit2(&payload); + assert_eq!(proof.signature, UPTO_SIGNATURE); + assert_eq!( + serde_json::to_value(&proof.permit2_authorization).unwrap(), + json!({ + "from": EVM_ADDRESS, + "permitted": {"token": "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913", "amount": "3600"}, + "spender": "0x4020A4f3b7b90ccA423B9fabCc0CE57C6C240002", + "nonce": NONCE, + "deadline": DEADLINE.to_string(), + "witness": { + "to": "0xb5194A98DbDBb7028B585Db26B972e7F0F3f826A", + "facilitator": "0x4c934c63C786157Fefd990945b25eA60a0FB0205", + "validAfter": "0" + } + }) + ); +} + +#[tokio::test] +async fn sufficient_allowance_echoes_the_server_extensions_without_a_permit() { + let transport = transport(vec![Ok(word(3600))]); + let challenge = twitr(); + let payload = build(&challenge, &transport).await.unwrap(); + + assert_eq!( + Value::Object(payload.extensions.clone()), + Value::Object(challenge.extensions.clone()), + "the reference client echoes the server's extensions unchanged" + ); + let calls = transport.calls.lock().unwrap(); + assert_eq!(calls.len(), 1, "only the allowance is read"); + assert_eq!(calls[0], (NetworkId::evm(8453), "eth_call".to_string())); + let params = transport.params.lock().unwrap(); + assert_eq!( + params[0][0]["to"], + "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913" + ); + let data = params[0][0]["data"].as_str().unwrap(); + assert!(data.starts_with("0xdd62ed3e") && data.ends_with(PERMIT2_CALLDATA_TAIL)); + assert_eq!(params[0][1], "latest"); +} + +#[tokio::test] +async fn insufficient_allowance_adds_a_signed_eip2612_permit_for_permit2() { + let transport = transport(vec![Ok(word(0)), Ok(word(7))]); + let challenge = twitr(); + let payload = build(&challenge, &transport).await.unwrap(); + + let sponsoring = &payload.extensions["eip2612GasSponsoring"]; + assert_eq!( + sponsoring["schema"], challenge.extensions["eip2612GasSponsoring"]["schema"], + "the server declaration is kept and the client info merged over it" + ); + assert!(payload.extensions.contains_key("bazaar")); + let info = &sponsoring["info"]; + assert_eq!(info["from"], EVM_ADDRESS); + assert_eq!(info["asset"], "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"); + assert_eq!( + info["spender"], + "0x000000000022D473030F116dDEE9F6B43aC78BA3" + ); + assert_eq!( + info["amount"], "3600", + "the proxy requires value == permitted.amount" + ); + assert_eq!(info["nonce"], "7"); + assert_eq!(info["deadline"], DEADLINE.to_string()); + assert_eq!(info["version"], "1"); + assert_eq!( + info["description"], + challenge.extensions["eip2612GasSponsoring"]["info"]["description"] + ); + assert_eq!( + info["signature"], + "0x706f8899c02a49c682945a1d4f208446276be6493c33d74742aa53d2eb88807a5502da544b4a8053c3e67202aa115aaa78cdfbf2f1e780a8aa7245bc6e115cf41b", + "the reference client's EIP-2612 signature for the same terms" + ); + + let permit = eip712::Eip2612Permit { + owner: evm_address_bytes(EVM_ADDRESS).unwrap(), + spender: eip712::PERMIT2, + value: eip712::u256_from_u64(3600), + nonce: eip712::u256_from_u64(7), + deadline: eip712::u256_from_u64(DEADLINE), + }; + let domain = eip712::domain_separator( + evm_address_bytes("0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913").unwrap(), + 8453, + "USD Coin", + "2", + ); + assert_eq!( + recover( + eip712::signing_digest(domain, permit.struct_hash()), + info["signature"].as_str().unwrap() + ), + payer_key() + ); + let params = transport.params.lock().unwrap(); + let nonce_call = params[1][0]["data"].as_str().unwrap(); + assert!(nonce_call.starts_with("0x7ecebe00")); +} + +#[tokio::test] +async fn an_unreadable_allowance_still_signs_the_permit() { + let unreachable = Err(TransportError::Unreachable { + network: NetworkId::evm(8453), + message: "down".into(), + }); + let transport = transport(vec![unreachable, Ok(word(0))]); + let payload = build(&twitr(), &transport).await.unwrap(); + assert_eq!( + payload.extensions["eip2612GasSponsoring"]["info"]["nonce"], + "0" + ); +} + +#[tokio::test] +async fn an_unreadable_token_nonce_fails_the_payment() { + let transport = transport(vec![Ok(word(0)), Ok(json!({"not": "a word"}))]); + let error = build(&twitr(), &transport).await.unwrap_err(); + assert!( + matches!(&error, X402Error::Wallet(message) if message.contains("EIP-2612 nonce")), + "{error}" + ); +} + +#[tokio::test] +async fn no_permit_is_read_or_signed_unless_the_server_sponsors_it() { + let mut challenge = twitr(); + challenge.extensions.remove("eip2612GasSponsoring"); + let transport = FakeTransport::default(); + let payload = build(&challenge, &transport).await.unwrap(); + assert!(transport.calls.lock().unwrap().is_empty()); + assert!(!payload.extensions.contains_key("eip2612GasSponsoring")); + assert!(payload.extensions.contains_key("bazaar")); +} + +#[tokio::test] +async fn no_permit_is_signed_without_the_token_domain() { + let mut challenge = twitr(); + let extra = challenge.accepts[0].extra.as_mut().unwrap(); + extra.version = None; + let transport = FakeTransport::default(); + let payload = build(&challenge, &transport).await.unwrap(); + assert!(transport.calls.lock().unwrap().is_empty()); + assert!( + payload.extensions["eip2612GasSponsoring"]["info"] + .get("signature") + .is_none() + ); +} + +#[tokio::test] +async fn a_bad_facilitator_or_recipient_is_a_protocol_error() { + for (field, value) in [("facilitator", "0x1234"), ("payTo", "nope")] { + let mut challenge = twitr(); + let requirement = &mut challenge.accepts[0]; + match field { + "facilitator" => { + requirement.extra.as_mut().unwrap().facilitator_address = Some(value.into()); + } + _ => requirement.pay_to = value.into(), + } + let error = build(&challenge, &FakeTransport::default()) + .await + .unwrap_err(); + assert!(matches!(error, X402Error::Protocol(_)), "{field}: {error}"); + } + let mut challenge = twitr(); + challenge.accepts[0] + .extra + .as_mut() + .unwrap() + .facilitator_address = None; + let error = build(&challenge, &FakeTransport::default()) + .await + .unwrap_err(); + assert!(error.to_string().contains("facilitatorAddress"), "{error}"); +} + +#[tokio::test] +async fn the_deadline_is_capped_like_an_eip3009_authorization() { + let mut challenge = twitr(); + challenge.accepts[0].max_timeout_seconds = 86_400; + let payload = build(&challenge, &transport(vec![Ok(word(u64::MAX))])) + .await + .unwrap(); + assert_eq!( + permit2(&payload).permit2_authorization.deadline, + (NOW + 300).to_string() + ); +} + +#[tokio::test] +async fn crypto_payments_pays_an_upto_requirement_with_a_permit2_proof() { + let transport = std::sync::Arc::new(transport(vec![Ok(word(u64::MAX))])); + let payments = + CryptoPayments::new(std::sync::Arc::new(FakePaymentSigner::default()), transport); + let challenge = twitr(); + let build = payments + .build_with_metadata(&challenge, &challenge.accepts[0], PaymentChain::Evm) + .await + .unwrap(); + let proof = permit2(&build.payload); + let deadline: i64 = proof.permit2_authorization.deadline.parse().unwrap(); + assert_eq!( + build.authorization_valid_until, + chrono::DateTime::from_timestamp(deadline, 0) + ); + assert_ne!(proof.permit2_authorization.nonce, NONCE, "a fresh nonce"); + let terms = upto_terms( + EVM_ADDRESS, + &challenge.accepts[0], + eip712::u256_from_decimal(&proof.permit2_authorization.nonce).unwrap(), + u64::try_from(deadline).unwrap() - 300, + ) + .unwrap(); + assert_eq!(recover(terms.digest(), &proof.signature), payer_key()); +} + +#[tokio::test] +async fn the_builder_refuses_a_transfer_method_other_than_permit2() { + // Selection already skips these; the builder is reachable directly through + // `pay_challenge_header`, so it checks again. + let mut challenge = twitr(); + challenge.accepts[0] + .extra + .as_mut() + .unwrap() + .asset_transfer_method = Some("eip3009".into()); + let error = build(&challenge, &FakeTransport::default()) + .await + .unwrap_err(); + assert!( + matches!(&error, X402Error::Protocol(m) if m.contains("assetTransferMethod")), + "{error}" + ); + + let mut absent = twitr(); + absent.accepts[0] + .extra + .as_mut() + .unwrap() + .asset_transfer_method = None; + assert!( + build(&absent, &transport(vec![Ok(word(u64::MAX))])) + .await + .is_ok() + ); +} + +#[tokio::test] +async fn wallet_and_requirement_failures_are_reported_before_anything_is_returned() { + let challenge = twitr(); + let failing = |signer: FakePaymentSigner| async move { + build_upto_payment_at( + &signer, + &FakeTransport::default(), + &twitr(), + &twitr().accepts[0], + eip712::u256_from_decimal(NONCE).unwrap(), + NOW, + ) + .await + .unwrap_err() + }; + let no_account = failing(FakePaymentSigner { + account_error: Some("locked".into()), + ..FakePaymentSigner::default() + }) + .await; + assert_eq!(no_account.to_string(), "x402 wallet: locked"); + let no_signature = failing(FakePaymentSigner { + sign_error: Some("refused".into()), + ..FakePaymentSigner::default() + }) + .await; + assert_eq!( + no_signature.to_string(), + "x402 wallet: sign Permit2: refused" + ); + let short_signature = failing(FakePaymentSigner { + signature_len: Some(10), + ..FakePaymentSigner::default() + }) + .await; + assert!(matches!(short_signature, X402Error::Wallet(_))); + + for edit in [ + |r: &mut crate::wire::PaymentRequirements| r.network = "solana:x".into(), + |r: &mut crate::wire::PaymentRequirements| r.amount = "lots".into(), + |r: &mut crate::wire::PaymentRequirements| r.asset = "0x12".into(), + ] { + let mut requirement = challenge.accepts[0].clone(); + edit(&mut requirement); + let error = upto_terms( + EVM_ADDRESS, + &requirement, + eip712::u256_from_decimal(NONCE).unwrap(), + NOW, + ) + .unwrap_err(); + assert!(matches!(error, X402Error::Protocol(_)), "{error}"); + } +} + +#[tokio::test] +async fn a_permit_the_wallet_cannot_sign_fails_the_payment() { + // The Permit2 signature succeeds; the EIP-2612 one is the second call. + struct SecondSignFails(FakePaymentSigner, std::sync::atomic::AtomicUsize); + #[async_trait::async_trait] + impl PaymentSigner for SecondSignFails { + async fn account( + &self, + chain: PaymentChain, + ) -> Result { + self.0.account(chain).await + } + async fn sign( + &self, + chain: PaymentChain, + message: &[u8], + scheme: SignScheme, + ) -> Result, String> { + if self.1.fetch_add(1, std::sync::atomic::Ordering::SeqCst) == 1 { + return Err("busy".into()); + } + self.0.sign(chain, message, scheme).await + } + } + let signer = SecondSignFails(FakePaymentSigner::default(), 0.into()); + let challenge = twitr(); + let error = build_upto_payment_at( + &signer, + &transport(vec![Ok(word(0)), Ok(word(0))]), + &challenge, + &challenge.accepts[0], + eip712::u256_from_decimal(NONCE).unwrap(), + NOW, + ) + .await + .unwrap_err(); + assert_eq!(error.to_string(), "x402 wallet: sign EIP-2612: busy"); +} diff --git a/crates/tinywallet-x402/src/eip712/mod.rs b/crates/tinywallet-x402/src/eip712/mod.rs index 5539eec2..054f3bb0 100644 --- a/crates/tinywallet-x402/src/eip712/mod.rs +++ b/crates/tinywallet-x402/src/eip712/mod.rs @@ -24,6 +24,12 @@ use sha3::{Digest, Keccak256}; +mod permit2; + +pub use permit2::{ + Eip2612Permit, PERMIT2, UPTO_PERMIT2_PROXY, UptoPermit, permit2_domain_separator, +}; + /// `keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)")`. /// /// Pinned rather than computed at each call: it is a published constant, and a @@ -99,6 +105,34 @@ pub fn u256_from_decimal(value: &str) -> Result { Ok(out) } +/// Print a 32-byte big-endian integer in base 10, the inverse of +/// [`u256_from_decimal`]. +/// +/// x402 carries Permit2 and EIP-2612 nonces as decimal strings, and a random +/// 256-bit nonce does not fit any primitive integer; this does the repeated +/// division by ten over the bytes instead. +#[must_use] +pub fn u256_to_decimal(value: &U256Bytes) -> String { + let mut remaining = *value; + let mut digits = Vec::new(); + while remaining.iter().any(|byte| *byte != 0) { + // remaining = remaining / 10, keeping the remainder, most significant + // byte first. + let mut carry = 0u32; + for byte in &mut remaining { + let current = (carry << 8) | u32::from(*byte); + *byte = u8::try_from(current / 10).unwrap_or(0); + carry = current % 10; + } + digits.push(b'0' + u8::try_from(carry).unwrap_or(0)); + } + if digits.is_empty() { + return "0".to_string(); + } + digits.reverse(); + String::from_utf8(digits).unwrap_or_default() +} + /// Why an EIP-712 payload could not be built. #[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] #[non_exhaustive] diff --git a/crates/tinywallet-x402/src/eip712/permit2.rs b/crates/tinywallet-x402/src/eip712/permit2.rs new file mode 100644 index 00000000..e7c23b81 --- /dev/null +++ b/crates/tinywallet-x402/src/eip712/permit2.rs @@ -0,0 +1,140 @@ +//! Permit2 `upto` authorizations, and the EIP-2612 `Permit` that lets a +//! facilitator approve Permit2 on the payer's behalf. +//! +//! The x402 `upto` scheme signs a Permit2 `PermitWitnessTransferFrom` whose +//! spender is the `x402UptoPermit2Proxy`. Its witness binds the recipient, the +//! one facilitator allowed to settle, and the start of the validity window, so +//! the proxy can move any amount up to `permitted.amount`, to that recipient +//! only, and only when that facilitator submits it. +//! +//! The type strings are those of the x402 reference client +//! (`uptoPermit2WitnessTypes` and `eip2612PermitTypes`); EIP-712 appends the +//! referenced struct types, sorted by name, to the primary type. + +use super::{Address20, U256Bytes, keccak, left_pad_address, u256_from_u64}; + +/// The canonical Permit2 contract, at the same address on every EVM chain. +pub const PERMIT2: Address20 = [ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x22, 0xd4, 0x73, 0x03, 0x0f, 0x11, 0x6d, 0xde, 0xe9, 0xf6, 0xb4, + 0x3a, 0xc7, 0x8b, 0xa3, +]; + +/// The `x402UptoPermit2Proxy`, the spender of every `upto` authorization. It +/// is deployed with CREATE2 to the same address on every supported chain. +pub const UPTO_PERMIT2_PROXY: Address20 = [ + 0x40, 0x20, 0xa4, 0xf3, 0xb7, 0xb9, 0x0c, 0xca, 0x42, 0x3b, 0x9f, 0xab, 0xcc, 0x0c, 0xe5, 0x7c, + 0x6c, 0x24, 0x00, 0x02, +]; + +/// Permit2's EIP-712 domain has a name but no version. +const PERMIT2_DOMAIN_TYPE: &[u8] = + b"EIP712Domain(string name,uint256 chainId,address verifyingContract)"; + +/// Permit2's `TokenPermissions` struct. +pub(super) const TOKEN_PERMISSIONS_TYPE: &[u8] = b"TokenPermissions(address token,uint256 amount)"; + +/// The `upto` witness struct. +const WITNESS_TYPE: &[u8] = b"Witness(address to,address facilitator,uint256 validAfter)"; + +/// The primary type with its referenced types appended in name order. +const PERMIT_WITNESS_TRANSFER_FROM_TYPE: &[u8] = b"PermitWitnessTransferFrom(TokenPermissions permitted,address spender,uint256 nonce,uint256 deadline,Witness witness)TokenPermissions(address token,uint256 amount)Witness(address to,address facilitator,uint256 validAfter)"; + +/// The EIP-2612 `Permit` struct. +pub(super) const PERMIT_TYPE: &[u8] = + b"Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"; + +/// The domain separator of the canonical Permit2 contract on `chain_id`. +#[must_use] +pub fn permit2_domain_separator(chain_id: u64) -> [u8; 32] { + let mut encoded = Vec::with_capacity(4 * 32); + encoded.extend_from_slice(&keccak(PERMIT2_DOMAIN_TYPE)); + encoded.extend_from_slice(&keccak(b"Permit2")); + encoded.extend_from_slice(&u256_from_u64(chain_id)); + encoded.extend_from_slice(&left_pad_address(PERMIT2)); + keccak(&encoded) +} + +/// A Permit2 `PermitWitnessTransferFrom` carrying the x402 `upto` witness. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct UptoPermit { + /// The token the proxy may move (`permitted.token`). + pub token: Address20, + /// The most the proxy may move (`permitted.amount`). + pub amount: U256Bytes, + /// Who may call Permit2 with this permit: [`UPTO_PERMIT2_PROXY`]. + pub spender: Address20, + /// Permit2's unordered nonce; any unused value. + pub nonce: U256Bytes, + /// Unix time after which the permit is void. + pub deadline: U256Bytes, + /// The only recipient the proxy may pay (`witness.to`). + pub to: Address20, + /// The only facilitator that may settle (`witness.facilitator`). + pub facilitator: Address20, + /// Unix time before which the permit is not yet valid + /// (`witness.validAfter`). + pub valid_after: U256Bytes, +} + +impl UptoPermit { + /// The EIP-712 struct hash, to be combined with + /// [`permit2_domain_separator`] by [`signing_digest`](super::signing_digest). + #[must_use] + pub fn struct_hash(&self) -> [u8; 32] { + let mut permitted = Vec::with_capacity(3 * 32); + permitted.extend_from_slice(&keccak(TOKEN_PERMISSIONS_TYPE)); + permitted.extend_from_slice(&left_pad_address(self.token)); + permitted.extend_from_slice(&self.amount); + + let mut witness = Vec::with_capacity(4 * 32); + witness.extend_from_slice(&keccak(WITNESS_TYPE)); + witness.extend_from_slice(&left_pad_address(self.to)); + witness.extend_from_slice(&left_pad_address(self.facilitator)); + witness.extend_from_slice(&self.valid_after); + + let mut encoded = Vec::with_capacity(6 * 32); + encoded.extend_from_slice(&keccak(PERMIT_WITNESS_TRANSFER_FROM_TYPE)); + encoded.extend_from_slice(&keccak(&permitted)); + encoded.extend_from_slice(&left_pad_address(self.spender)); + encoded.extend_from_slice(&self.nonce); + encoded.extend_from_slice(&self.deadline); + encoded.extend_from_slice(&keccak(&witness)); + keccak(&encoded) + } +} + +/// An EIP-2612 `Permit`: the token holder approves `spender` without a +/// transaction. Hash it under the token's own domain +/// ([`domain_separator`](super::domain_separator)). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Eip2612Permit { + /// The token holder. + pub owner: Address20, + /// The approved spender: [`PERMIT2`] for x402 gas sponsoring. + pub spender: Address20, + /// The allowance granted. + pub value: U256Bytes, + /// The holder's current `nonces(owner)` on the token. + pub nonce: U256Bytes, + /// Unix time after which the permit is void. + pub deadline: U256Bytes, +} + +impl Eip2612Permit { + /// The EIP-712 struct hash. + #[must_use] + pub fn struct_hash(&self) -> [u8; 32] { + let mut encoded = Vec::with_capacity(6 * 32); + encoded.extend_from_slice(&keccak(PERMIT_TYPE)); + encoded.extend_from_slice(&left_pad_address(self.owner)); + encoded.extend_from_slice(&left_pad_address(self.spender)); + encoded.extend_from_slice(&self.value); + encoded.extend_from_slice(&self.nonce); + encoded.extend_from_slice(&self.deadline); + keccak(&encoded) + } +} + +#[cfg(test)] +#[path = "permit2_tests.rs"] +mod tests; diff --git a/crates/tinywallet-x402/src/eip712/permit2_tests.rs b/crates/tinywallet-x402/src/eip712/permit2_tests.rs new file mode 100644 index 00000000..81247772 --- /dev/null +++ b/crates/tinywallet-x402/src/eip712/permit2_tests.rs @@ -0,0 +1,147 @@ +//! Tests for the Permit2 `upto` witness and EIP-2612 `Permit` hashing. +//! +//! The digests are not this module's own output played back: they were +//! computed by viem's `hashTypedData` (the library the x402 reference client +//! signs with) over the reference implementation's own type definitions +//! (`uptoPermit2WitnessTypes`, `eip2612PermitTypes` in coinbase/x402 +//! `typescript/packages/mechanisms/evm/src/constants.ts`). The signatures are +//! viem's `signTypedData` with the BIP-39 vector account, and k256 signs +//! deterministically (RFC 6979) exactly as viem does, so they must match too. + +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use super::super::{keccak, signing_digest, u256_from_decimal, u256_from_u64}; +use super::*; + +fn hex(bytes: &[u8]) -> String { + bytes.iter().fold(String::new(), |mut out, b| { + use std::fmt::Write as _; + let _ = write!(out, "{b:02x}"); + out + }) +} + +fn address(text: &str) -> [u8; 20] { + let body = text.trim_start_matches("0x"); + let mut out = [0u8; 20]; + for (index, slot) in out.iter_mut().enumerate() { + *slot = u8::from_str_radix(&body[index * 2..index * 2 + 2], 16).unwrap(); + } + out +} + +const USDC_BASE: &str = "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"; +const PAYER: &str = "0x9858EfFD232B4033E47d90003D41EC34EcaEda94"; + +/// The twitr.sh volume-tool terms with a fixed nonce and deadline. +fn twitr_permit() -> UptoPermit { + UptoPermit { + token: address(USDC_BASE), + amount: u256_from_u64(3600), + spender: UPTO_PERMIT2_PROXY, + nonce: u256_from_decimal( + "33247007178036348590600198031289925668252061821958005840077069883511451257277", + ) + .unwrap(), + deadline: u256_from_u64(1_740_672_154), + to: address("0xb5194A98DbDBb7028B585Db26B972e7F0F3f826A"), + facilitator: address("0x4c934c63C786157Fefd990945b25eA60a0FB0205"), + valid_after: u256_from_u64(0), + } +} + +#[test] +fn the_pinned_addresses_are_the_canonical_contracts() { + assert_eq!( + hex(&PERMIT2), + "000000000022d473030f116ddee9f6b43ac78ba3", + "canonical Permit2" + ); + assert_eq!( + hex(&UPTO_PERMIT2_PROXY), + "4020a4f3b7b90cca423b9fabcc0ce57c6c240002", + "x402UptoPermit2Proxy" + ); +} + +#[test] +fn the_token_permissions_type_hash_is_permit2s_constant() { + // `_TOKEN_PERMISSIONS_TYPEHASH` in Uniswap's PermitHash.sol. + assert_eq!( + hex(&keccak(TOKEN_PERMISSIONS_TYPE)), + "618358ac3db8dc274f0cd8829da7e234bd48cd73c4a740aede1adec9846d06a1" + ); +} + +#[test] +fn the_eip2612_permit_type_hash_is_the_published_constant() { + // `PERMIT_TYPEHASH` from EIP-2612. + assert_eq!( + hex(&keccak(PERMIT_TYPE)), + "6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9" + ); +} + +#[test] +fn the_upto_digest_matches_the_reference_client() { + let digest = signing_digest(permit2_domain_separator(8453), twitr_permit().struct_hash()); + assert_eq!( + hex(&digest), + "8e8c28bb23e744c0eb81bdfab664afc6c046d317a33873fdf0ffa275ecee94f9" + ); +} + +#[test] +fn every_upto_field_is_bound_into_the_digest() { + let base = twitr_permit().struct_hash(); + let changes: [fn(&mut UptoPermit); 8] = [ + |p| p.token[19] ^= 1, + |p| p.amount[31] ^= 1, + |p| p.spender[19] ^= 1, + |p| p.nonce[31] ^= 1, + |p| p.deadline[31] ^= 1, + |p| p.to[19] ^= 1, + |p| p.facilitator[19] ^= 1, + |p| p.valid_after[31] ^= 1, + ]; + for change in changes { + let mut permit = twitr_permit(); + change(&mut permit); + assert_ne!(permit.struct_hash(), base); + } + assert_ne!( + permit2_domain_separator(8453), + permit2_domain_separator(84532) + ); +} + +#[test] +fn the_eip2612_digest_matches_the_reference_client() { + let permit = Eip2612Permit { + owner: address(PAYER), + spender: PERMIT2, + value: u256_from_u64(3600), + nonce: u256_from_u64(7), + deadline: u256_from_u64(1_740_672_154), + }; + let domain = super::super::domain_separator(address(USDC_BASE), 8453, "USD Coin", "2"); + assert_eq!( + hex(&signing_digest(domain, permit.struct_hash())), + "f4935bb06c8d01cdab90133ce4a8c1040124320fb214773633ebaa37b3883cbe" + ); +} + +#[test] +fn a_uint256_prints_as_the_decimal_it_was_parsed_from() { + for text in [ + "0", + "3600", + "33247007178036348590600198031289925668252061821958005840077069883511451257277", + "115792089237316195423570985008687907853269984665640564039457584007913129639935", + ] { + assert_eq!( + super::super::u256_to_decimal(&u256_from_decimal(text).unwrap()), + text + ); + } +} diff --git a/crates/tinywallet-x402/src/ledger/mod.rs b/crates/tinywallet-x402/src/ledger/mod.rs index 1d283734..f3353be8 100644 --- a/crates/tinywallet-x402/src/ledger/mod.rs +++ b/crates/tinywallet-x402/src/ledger/mod.rs @@ -95,3 +95,7 @@ mod holds_test; #[cfg(test)] #[path = "mod_paging_tests.rs"] mod paging_test; + +#[cfg(test)] +#[path = "mod_upto_tests.rs"] +mod upto_tests; diff --git a/crates/tinywallet-x402/src/ledger/mod_authorization_tests.rs b/crates/tinywallet-x402/src/ledger/mod_authorization_tests.rs index c98b3859..216d7390 100644 --- a/crates/tinywallet-x402/src/ledger/mod_authorization_tests.rs +++ b/crates/tinywallet-x402/src/ledger/mod_authorization_tests.rs @@ -51,6 +51,7 @@ fn record( authorization_expiry_observed_height: None, session_id: session.into(), thread_id: None, + scheme: None, } } diff --git a/crates/tinywallet-x402/src/ledger/mod_holds_tests.rs b/crates/tinywallet-x402/src/ledger/mod_holds_tests.rs index 20e0dca8..493fbae8 100644 --- a/crates/tinywallet-x402/src/ledger/mod_holds_tests.rs +++ b/crates/tinywallet-x402/src/ledger/mod_holds_tests.rs @@ -50,6 +50,7 @@ fn settled(amount: u64) -> PaymentRecord { authorization_expiry_observed_height: None, session_id: "other".into(), thread_id: None, + scheme: None, } } diff --git a/crates/tinywallet-x402/src/ledger/mod_paging_tests.rs b/crates/tinywallet-x402/src/ledger/mod_paging_tests.rs index 6b4d469a..5150fbbf 100644 --- a/crates/tinywallet-x402/src/ledger/mod_paging_tests.rs +++ b/crates/tinywallet-x402/src/ledger/mod_paging_tests.rs @@ -24,6 +24,7 @@ fn settled(amount: u64) -> PaymentRecord { authorization_expiry_observed_height: None, session_id: "session-paging".into(), thread_id: None, + scheme: None, } } diff --git a/crates/tinywallet-x402/src/ledger/mod_tests.rs b/crates/tinywallet-x402/src/ledger/mod_tests.rs index ec4ef134..24834b12 100644 --- a/crates/tinywallet-x402/src/ledger/mod_tests.rs +++ b/crates/tinywallet-x402/src/ledger/mod_tests.rs @@ -56,6 +56,7 @@ fn record( authorization_expiry_observed_height: None, session_id: session.into(), thread_id: None, + scheme: None, } } diff --git a/crates/tinywallet-x402/src/ledger/mod_upto_tests.rs b/crates/tinywallet-x402/src/ledger/mod_upto_tests.rs new file mode 100644 index 00000000..e37c96e4 --- /dev/null +++ b/crates/tinywallet-x402/src/ledger/mod_upto_tests.rs @@ -0,0 +1,75 @@ +//! Tests for `upto` payments in the ledger: the scheme is kept with the +//! record, and settling for less than the signed ceiling frees the rest. + +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use chrono::Utc; + +use super::*; + +fn budget() -> SpendingBudget { + SpendingBudget { + per_request_max_atomic: 10_000, + daily_max_atomic: 10_000, + monthly_max_atomic: 100_000, + } +} + +fn upto(status: PaymentStatus, amount: u64) -> PaymentRecord { + PaymentRecord { + id: "upto-1".into(), + url: "https://twitr.sh/api/tools/x_search".into(), + asset: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913".into(), + amount_atomic: amount, + amount_display: format_usdc(amount), + recipient: "0xb5194A98DbDBb7028B585Db26B972e7F0F3f826A".into(), + network: "eip155:8453".into(), + tx_signature: None, + status, + timestamp: Utc::now(), + authorization_valid_until: Some(Utc::now() + chrono::Duration::minutes(5)), + solana_last_valid_block_height: None, + authorization_expired_at: None, + authorization_expiry_observed_height: None, + session_id: "s".into(), + thread_id: None, + scheme: Some("upto".into()), + } +} + +#[test] +fn the_scheme_survives_a_reopen() { + let storage = LedgerStorage::memory(); + let mut ledger = PaymentLedger::open(storage.clone(), "s", budget()).unwrap(); + ledger + .try_record_payment(upto(PaymentStatus::Pending, 3600)) + .unwrap(); + drop(ledger); + let reopened = PaymentLedger::open(storage, "s", budget()).unwrap(); + assert_eq!( + reopened.payment("upto-1").unwrap().scheme.as_deref(), + Some("upto") + ); +} + +#[test] +fn settling_below_the_ceiling_releases_the_rest_of_the_budget() { + for actual in [1200, 0] { + let mut ledger = PaymentLedger::open(LedgerStorage::memory(), "s", budget()).unwrap(); + ledger + .try_record_payment(upto(PaymentStatus::Pending, 3600)) + .unwrap(); + assert_eq!(ledger.outstanding_atomic(), 3600); + assert!( + ledger.check_budget(10_000 - 3600 + 1).refusal().is_some(), + "the pending ceiling is held" + ); + + ledger + .try_record_payment(upto(PaymentStatus::Settled, actual)) + .unwrap(); + assert_eq!(ledger.outstanding_atomic(), 0); + assert_eq!(ledger.summary().daily_total_atomic, actual); + assert_eq!(ledger.check_budget(10_000 - actual), BudgetCheck::Allowed); + } +} diff --git a/crates/tinywallet-x402/src/ledger/persist.rs b/crates/tinywallet-x402/src/ledger/persist.rs index d49242b0..7c1a9d11 100644 --- a/crates/tinywallet-x402/src/ledger/persist.rs +++ b/crates/tinywallet-x402/src/ledger/persist.rs @@ -110,6 +110,7 @@ pub(super) fn stored_payment( authorization_expiry_observed_height: record.authorization_expiry_observed_height, session_id: record.session_id.clone(), thread_id: record.thread_id.clone(), + scheme: record.scheme.clone(), committed_hold: committed_hold.map(str::to_owned), } } @@ -141,6 +142,7 @@ pub(super) fn into_record( authorization_expiry_observed_height: stored.authorization_expiry_observed_height, session_id: stored.session_id, thread_id: stored.thread_id, + scheme: stored.scheme, }; Ok((record, stored.committed_hold)) } diff --git a/crates/tinywallet-x402/src/ledger/schema_payment.rs b/crates/tinywallet-x402/src/ledger/schema_payment.rs index 1cde5906..f349df6e 100644 --- a/crates/tinywallet-x402/src/ledger/schema_payment.rs +++ b/crates/tinywallet-x402/src/ledger/schema_payment.rs @@ -99,6 +99,8 @@ impl From for StoredPaymentRecord { authorization_expiry_observed_height: legacy.authorization_expiry_observed_height, session_id: legacy.session_id, thread_id: legacy.thread_id, + // Legacy rows predate `upto`; every one of them was `exact`. + scheme: None, committed_hold: legacy.committed_hold, } } diff --git a/crates/tinywallet-x402/src/ledger/store.rs b/crates/tinywallet-x402/src/ledger/store.rs index f556227c..0df8cb7a 100644 --- a/crates/tinywallet-x402/src/ledger/store.rs +++ b/crates/tinywallet-x402/src/ledger/store.rs @@ -530,6 +530,16 @@ impl PaymentLedger { self.records.iter().rev().take(limit).cloned().collect() } + /// Read the records other writers appended since this ledger last looked, + /// so a following [`payment`](Self::payment) sees the latest state. + /// + /// # Errors + /// + /// Returns an error if the payments stream cannot be read. + pub fn refresh(&mut self) -> Result<(), String> { + self.refresh_records() + } + /// Return the latest recorded state for a payment id. #[must_use] pub fn payment(&self, id: &str) -> Option<&PaymentRecord> { diff --git a/crates/tinywallet-x402/src/ledger/types.rs b/crates/tinywallet-x402/src/ledger/types.rs index bd0754b0..1ddc313d 100644 --- a/crates/tinywallet-x402/src/ledger/types.rs +++ b/crates/tinywallet-x402/src/ledger/types.rs @@ -66,6 +66,11 @@ pub struct PaymentRecord { /// reported one. Absent from older ledger files. #[serde(default, skip_serializing_if = "Option::is_none")] pub thread_id: Option, + /// The x402 scheme the authorization was signed under (`exact`, `upto`). + /// Absent from older records, which were all `exact`. An `upto` record + /// holds the signed ceiling until its receipt reports what was charged. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub scheme: Option, } impl PaymentRecord { diff --git a/crates/tinywallet-x402/src/protocol/builder.rs b/crates/tinywallet-x402/src/protocol/builder.rs index f513631a..cc4bf690 100644 --- a/crates/tinywallet-x402/src/protocol/builder.rs +++ b/crates/tinywallet-x402/src/protocol/builder.rs @@ -4,9 +4,7 @@ use async_trait::async_trait; use chrono::{DateTime, Utc}; use super::error::X402Error; -use crate::wire::{ - PaymentChain, PaymentPayload, PaymentProof, PaymentRequired, PaymentRequirements, -}; +use crate::wire::{PaymentChain, PaymentPayload, PaymentRequired, PaymentRequirements}; /// Rail-specific metadata that stays in the host ledger and is never added to /// the facilitator-facing payment payload. @@ -51,15 +49,10 @@ pub trait PaymentBuilder: Send + Sync { chain: PaymentChain, ) -> Result { let payload = self.build(challenge, requirement, chain).await?; - let authorization_valid_until = match &payload.payload { - PaymentProof::Evm(proof) => proof - .authorization - .valid_before - .parse::() - .ok() - .and_then(|seconds| DateTime::from_timestamp(seconds, 0)), - PaymentProof::Solana(_) => None, - }; + let authorization_valid_until = payload + .payload + .authorization_deadline_secs() + .and_then(|seconds| DateTime::from_timestamp(seconds, 0)); Ok(PaymentBuild { payload, authorization_valid_until, diff --git a/crates/tinywallet-x402/src/protocol/client.rs b/crates/tinywallet-x402/src/protocol/client.rs index 9fc72512..58e248bc 100644 --- a/crates/tinywallet-x402/src/protocol/client.rs +++ b/crates/tinywallet-x402/src/protocol/client.rs @@ -88,7 +88,7 @@ impl X402Client { challenge.accepts.len() ); - let (index, chain) = select_requirement(&challenge)?; + let (index, chain) = select_requirement(&challenge, None)?; let requirement = &challenge.accepts[index]; let amount = parse_amount(requirement)?; @@ -161,7 +161,7 @@ pub fn handle_402( headers: &HeaderMap, ) -> Result<(PaymentRequired, usize, PaymentChain), X402Error> { let challenge = parse_402_headers(headers)?; - let (idx, chain) = select_requirement(&challenge)?; + let (idx, chain) = select_requirement(&challenge, None)?; Ok((challenge, idx, chain)) } @@ -198,7 +198,8 @@ pub async fn pay_challenge_header( pub struct X402PaymentResult { /// The `PAYMENT-SIGNATURE` header value. pub header_value: String, - /// The amount, in atomic units of `asset`. + /// The amount signed for, in atomic units of `asset`: the exact price, or + /// the ceiling of an `upto` payment. The budget holds this amount. pub amount_atomic: u64, /// The asset paid in. pub asset: String, @@ -206,6 +207,10 @@ pub struct X402PaymentResult { pub recipient: String, /// The CAIP-2 network the payment is on. pub network: String, + /// The x402 scheme signed under. For `upto`, [`amount_atomic`](Self::amount_atomic) + /// is the ceiling; the receipt reports what was charged (see + /// [`settled_amount`](super::settled_amount)). + pub scheme: String, /// The URL the payment is for. pub url: String, /// Expiry of the authorization when its rail has an explicit deadline. @@ -277,7 +282,35 @@ where F: FnOnce(String, PaymentRequirements, PaymentChain, u64) -> Fut, Fut: Future>, { - let (challenge, idx, chain) = handle_402(response_headers)?; + handle_402_and_pay_on_network(builder, response_headers, request_url, None, authorize).await +} + +/// [`handle_402_and_pay_authorized`], restricted to the options on `network`. +/// +/// `network` is a CAIP-2 chain id (`eip155:8453`) that an option's network +/// must equal, or a CAIP-2 namespace (`eip155`, `solana`) it must belong to. +/// `None` is exactly [`handle_402_and_pay_authorized`]. A caller pins the +/// network when the server ties the request to the paying account, for +/// example to an EVM identity it signed in with. +/// +/// # Errors +/// +/// As [`handle_402_and_pay_authorized`], plus +/// [`X402Error::NoPaymentOptionOnNetwork`] when no option is on `network`. +/// Nothing is held or signed in that case. +pub async fn handle_402_and_pay_on_network( + builder: &dyn PaymentBuilder, + response_headers: &HeaderMap, + request_url: &str, + network: Option<&str>, + authorize: F, +) -> Result +where + F: FnOnce(String, PaymentRequirements, PaymentChain, u64) -> Fut, + Fut: Future>, +{ + let challenge = parse_402_headers(response_headers)?; + let (idx, chain) = select_requirement(&challenge, network)?; let requirement = challenge.accepts[idx].clone(); let amount = parse_amount(&requirement)?; ensure_same_origin(&challenge.resource.url, request_url)?; @@ -328,6 +361,7 @@ where asset: requirement.asset.clone(), recipient: requirement.pay_to.clone(), network: requirement.network.clone(), + scheme: requirement.scheme.clone(), url: request_url.to_string(), authorization_valid_until: payment.authorization_valid_until, solana_last_valid_block_height: payment.solana_last_valid_block_height, diff --git a/crates/tinywallet-x402/src/protocol/error.rs b/crates/tinywallet-x402/src/protocol/error.rs index 12ed8bb3..89be34ec 100644 --- a/crates/tinywallet-x402/src/protocol/error.rs +++ b/crates/tinywallet-x402/src/protocol/error.rs @@ -14,8 +14,14 @@ pub enum X402Error { #[error("402 response missing PAYMENT-REQUIRED header")] NoPaymentHeader, /// The challenge offers nothing this crate can pay. - #[error("no supported payment option (Solana exact or EVM exact) in 402 challenge")] + #[error("no supported payment option (Solana exact, EVM exact or EVM upto) in 402 challenge")] NoPaymentOption, + /// The caller pinned a network, and the challenge offers nothing on it. + #[error("no supported payment option on {network} in 402 challenge")] + NoPaymentOptionOnNetwork { + /// The CAIP-2 network or namespace the caller pinned. + network: String, + }, /// One request would cost more than the per-request cap. #[error("x402 amount {requested} exceeds per-request cap {cap}")] AmountExceedsCap { @@ -56,6 +62,13 @@ pub enum X402Error { /// The challenge or a header could not be understood. #[error("x402 protocol: {0}")] Protocol(String), + /// A `sign-in-with-x` challenge asked for something this crate will not + /// sign, such as a message for another host or one already expired. + #[error("x402 sign-in-with-x refused: {reason}")] + SignInRefused { + /// Why the challenge was refused. + reason: String, + }, /// The wallet could not produce the payment. #[error("x402 wallet: {0}")] Wallet(String), diff --git a/crates/tinywallet-x402/src/protocol/headers.rs b/crates/tinywallet-x402/src/protocol/headers.rs index 0e76271e..ecea28fe 100644 --- a/crates/tinywallet-x402/src/protocol/headers.rs +++ b/crates/tinywallet-x402/src/protocol/headers.rs @@ -58,16 +58,42 @@ pub fn parse_settlement_response(b64_str: &str) -> Result bool { - receipt.success - && receipt.network == network - && receipt - .amount - .as_deref() - .is_none_or(|amount| amount.parse::() == Ok(amount_atomic)) + settled_amount(receipt, network, None, amount_atomic).is_some() +} + +/// The atomic amount `receipt` says was charged for a payment signed for +/// `signed_atomic` under `scheme`, or `None` when it does not settle it. +/// +/// A receipt settles only when it succeeded on the payment's network. Then: +/// +/// - `upto`: the reported `amount`, which may be anything from zero to the +/// signed ceiling. A larger or unreadable amount settles nothing. A receipt +/// without one (the field is required for `upto`) counts the whole ceiling. +/// - `exact`, or no scheme recorded: the signed amount, and only if the +/// receipt names no amount or exactly that one, so a receipt cannot make an +/// exact payment look cheaper than what was signed. +#[must_use] +pub fn settled_amount( + receipt: &SettlementResponse, + network: &str, + scheme: Option<&str>, + signed_atomic: u64, +) -> Option { + if !receipt.success || receipt.network != network { + return None; + } + let reported = receipt.amount.as_deref().map(str::parse::); + match (scheme, reported) { + (_, None) => Some(signed_atomic), + (Some("upto"), Some(Ok(actual))) => (actual <= signed_atomic).then_some(actual), + (Some("upto"), Some(Err(_))) => None, + (_, Some(reported)) => (reported == Ok(signed_atomic)).then_some(signed_atomic), + } } /// Encode a payment proof as the `PAYMENT-SIGNATURE` header value. @@ -80,3 +106,7 @@ pub fn encode_payment(payment: &PaymentPayload) -> Result { .map(|json| B64.encode(json)) .map_err(|e| X402Error::Protocol(format!("serialize payment: {e}"))) } + +#[cfg(test)] +#[path = "headers_tests.rs"] +mod tests; diff --git a/crates/tinywallet-x402/src/protocol/headers_tests.rs b/crates/tinywallet-x402/src/protocol/headers_tests.rs new file mode 100644 index 00000000..4332623b --- /dev/null +++ b/crates/tinywallet-x402/src/protocol/headers_tests.rs @@ -0,0 +1,84 @@ +//! Tests for reading the amount a settlement receipt actually charged. + +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use super::*; + +fn receipt(success: bool, network: &str, amount: Option<&str>) -> SettlementResponse { + SettlementResponse { + success, + transaction: String::new(), + network: network.into(), + payer: None, + error_reason: None, + amount: amount.map(Into::into), + extensions: serde_json::Map::new(), + } +} + +const BASE: &str = "eip155:8453"; + +#[test] +fn an_upto_receipt_settles_for_the_amount_it_reports() { + let cases = [ + (Some("1200"), Some(1200)), + (Some("0"), Some(0)), + (Some("3600"), Some(3600)), + (Some("3601"), None), + (Some("-1"), None), + (Some("lots"), None), + // `amount` is required for upto; without it, count the signed ceiling. + (None, Some(3600)), + ]; + for (reported, settled) in cases { + assert_eq!( + settled_amount(&receipt(true, BASE, reported), BASE, Some("upto"), 3600), + settled, + "{reported:?}" + ); + } +} + +#[test] +fn an_exact_receipt_must_report_the_signed_amount() { + for scheme in [None, Some("exact")] { + assert_eq!( + settled_amount(&receipt(true, BASE, Some("2500")), BASE, scheme, 2500), + Some(2500) + ); + assert_eq!( + settled_amount(&receipt(true, BASE, None), BASE, scheme, 2500), + Some(2500) + ); + assert_eq!( + settled_amount(&receipt(true, BASE, Some("1")), BASE, scheme, 2500), + None, + "an exact payment cannot be under-reported" + ); + } +} + +#[test] +fn a_failed_or_foreign_receipt_settles_nothing() { + assert_eq!( + settled_amount(&receipt(false, BASE, Some("1")), BASE, Some("upto"), 3600), + None + ); + assert_eq!( + settled_amount( + &receipt(true, "eip155:1", Some("1")), + BASE, + Some("upto"), + 3600 + ), + None + ); +} + +#[test] +fn settles_is_the_exact_rule() { + assert!(settles(&receipt(true, BASE, Some("2500")), BASE, 2500)); + assert!(settles(&receipt(true, BASE, None), BASE, 2500)); + assert!(!settles(&receipt(true, BASE, Some("2499")), BASE, 2500)); + assert!(!settles(&receipt(false, BASE, Some("2500")), BASE, 2500)); +} diff --git a/crates/tinywallet-x402/src/protocol/mod.rs b/crates/tinywallet-x402/src/protocol/mod.rs index b78d738d..cf8b5c22 100644 --- a/crates/tinywallet-x402/src/protocol/mod.rs +++ b/crates/tinywallet-x402/src/protocol/mod.rs @@ -25,10 +25,12 @@ mod select; pub use builder::{PaymentBuild, PaymentBuilder}; pub use client::{ X402Client, X402PaymentResult, handle_402, handle_402_and_pay, handle_402_and_pay_authorized, - pay_challenge_header, refresh_solana_authorizations, + handle_402_and_pay_on_network, pay_challenge_header, refresh_solana_authorizations, }; pub use error::X402Error; -pub use headers::{encode_payment, parse_402_headers, parse_settlement_response, settles}; +pub use headers::{ + encode_payment, parse_402_headers, parse_settlement_response, settled_amount, settles, +}; pub use proxy::ProxyPolicy; pub(crate) const LOG_PREFIX: &str = "[x402]"; @@ -36,3 +38,7 @@ pub(crate) const LOG_PREFIX: &str = "[x402]"; #[cfg(test)] #[path = "mod_tests.rs"] mod test; + +#[cfg(test)] +#[path = "mod_network_tests.rs"] +mod network_test; diff --git a/crates/tinywallet-x402/src/protocol/mod_network_tests.rs b/crates/tinywallet-x402/src/protocol/mod_network_tests.rs new file mode 100644 index 00000000..9d57dd8f --- /dev/null +++ b/crates/tinywallet-x402/src/protocol/mod_network_tests.rs @@ -0,0 +1,99 @@ +//! Tests for paying a challenge on a caller-pinned network. + +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use std::sync::Arc; + +use base64::Engine as _; +use base64::engine::general_purpose::STANDARD as B64; +use reqwest::header::{HeaderMap, HeaderValue}; + +use super::*; +use crate::crypto::{CryptoPayments, PaymentSigner}; +use crate::ledger::{self, SpendingBudget}; +use crate::test_support::{ + FakePaymentSigner, FakeTransport, challenge, challenge_header, evm_requirement, + solana_requirement, +}; +use crate::wire::{BASE_MAINNET_CAIP2, PaymentChain, PaymentPayload, PaymentProof}; + +const REQUEST_URL: &str = "https://x402.example.test/a"; + +fn headers(accepts: Vec) -> HeaderMap { + let mut headers = HeaderMap::new(); + let value = challenge_header(&challenge(accepts)); + headers.insert("payment-required", HeaderValue::from_str(&value).unwrap()); + headers +} + +fn payments() -> CryptoPayments { + let signer: Arc = Arc::new(FakePaymentSigner::default()); + CryptoPayments::new(signer, Arc::new(FakeTransport::default())) +} + +#[tokio::test] +async fn a_pinned_network_is_paid_even_when_another_is_preferred() { + let _guard = ledger::TEST_LOCK.lock().await; + ledger::init_global( + ledger::LedgerStorage::memory(), + "test-session", + SpendingBudget::default(), + ) + .unwrap(); + + let result = handle_402_and_pay_on_network( + &payments(), + &headers(vec![solana_requirement(), evm_requirement()]), + REQUEST_URL, + Some(BASE_MAINNET_CAIP2), + |_, requirement, chain, _| async move { + assert_eq!(requirement.network, BASE_MAINNET_CAIP2); + assert_eq!(chain, PaymentChain::Evm); + Ok(()) + }, + ) + .await + .unwrap(); + + assert_eq!(result.network, BASE_MAINNET_CAIP2); + assert_eq!(result.amount_atomic, 2_500); + let payload: PaymentPayload = + serde_json::from_slice(&B64.decode(&result.header_value).unwrap()).unwrap(); + assert!(matches!(payload.payload, PaymentProof::Evm(_))); + drop(result); + ledger::reset_global(); +} + +#[tokio::test] +async fn a_pin_the_challenge_cannot_meet_holds_and_signs_nothing() { + let _guard = ledger::TEST_LOCK.lock().await; + ledger::init_global( + ledger::LedgerStorage::memory(), + "test-session", + SpendingBudget::default(), + ) + .unwrap(); + let signer = Arc::new(FakePaymentSigner::default()); + let builder = CryptoPayments::new(signer.clone(), Arc::new(FakeTransport::default())); + + let error = handle_402_and_pay_on_network( + &builder, + &headers(vec![solana_requirement()]), + REQUEST_URL, + Some("eip155"), + |_, _, _, _| async { panic!("nothing may be approved") }, + ) + .await + .unwrap_err(); + + assert_eq!( + error.to_string(), + "no supported payment option on eip155 in 402 challenge" + ); + assert_eq!( + ledger::with_ledger(ledger::PaymentLedger::reserved_atomic).unwrap(), + 0 + ); + assert!(signer.sign_calls.lock().unwrap().is_empty()); + ledger::reset_global(); +} diff --git a/crates/tinywallet-x402/src/protocol/mod_tests.rs b/crates/tinywallet-x402/src/protocol/mod_tests.rs index 44256c66..efaa40fb 100644 --- a/crates/tinywallet-x402/src/protocol/mod_tests.rs +++ b/crates/tinywallet-x402/src/protocol/mod_tests.rs @@ -192,6 +192,7 @@ fn settled(amount: u64) -> PaymentRecord { authorization_expiry_observed_height: None, session_id: "test-session".into(), thread_id: None, + scheme: None, } } @@ -474,7 +475,13 @@ fn every_error_has_its_pinned_message() { let cases = [ ( X402Error::NoPaymentOption, - "no supported payment option (Solana exact or EVM exact) in 402 challenge", + "no supported payment option (Solana exact, EVM exact or EVM upto) in 402 challenge", + ), + ( + X402Error::NoPaymentOptionOnNetwork { + network: "eip155:8453".into(), + }, + "no supported payment option on eip155:8453 in 402 challenge", ), ( X402Error::AmountExceedsCap { @@ -932,7 +939,7 @@ async fn a_402_is_paid_and_retried_with_the_same_request() { serde_json::from_slice(&B64.decode(retry.payment_signature().unwrap()).unwrap()).unwrap(); match payload.payload { PaymentProof::Evm(evm) => assert_eq!(evm.authorization.value, "2500"), - PaymentProof::Solana(_) => panic!("expected an EVM proof"), + other => panic!("expected an EVM proof, got {other:?}"), } } diff --git a/crates/tinywallet-x402/src/protocol/select.rs b/crates/tinywallet-x402/src/protocol/select.rs index 9c4b9aba..20ec4af0 100644 --- a/crates/tinywallet-x402/src/protocol/select.rs +++ b/crates/tinywallet-x402/src/protocol/select.rs @@ -32,40 +32,100 @@ pub(crate) fn ensure_payable(requirement: &PaymentRequirements) -> Result<(), X4 } } -/// The index and chain of the requirement to pay: the first payable Solana -/// `exact` option, else the first payable EVM one. +/// Whether `network` falls under the caller's pin: a pin with a `:` is a full +/// CAIP-2 chain id and must match exactly; a pin without one is a CAIP-2 +/// namespace (`eip155`, `solana`) and matches every chain in it. +fn matches_pin(network: &str, pin: &str) -> bool { + if pin.contains(':') { + network == pin + } else { + network.split(':').next() == Some(pin) + } +} + +/// Whether an `upto` requirement carries what a Permit2 authorization needs: +/// an EVM network, a facilitator address to bind into the witness, and no +/// transfer method other than Permit2 (the only one `upto` allows; absent +/// means Permit2). Anything else is refused rather than guessed at. +fn is_payable_upto(requirement: &PaymentRequirements) -> bool { + let Some(extra) = requirement.extra.as_ref() else { + return false; + }; + requirement.evm_chain_id().is_some() + && extra + .asset_transfer_method + .as_deref() + .is_none_or(|method| method == "permit2") + && extra + .facilitator_address + .as_deref() + .is_some_and(|address| tinywallet_crypto::address::evm::validate(address).is_ok()) +} + +/// How strongly a requirement is preferred, best first, or `None` when this +/// crate cannot pay it at all. +/// +/// Solana `exact` first, then EVM `exact`, then EVM `upto`: a fixed price is +/// preferred to a ceiling, which keeps today's choice for every challenge +/// that offers `exact`. +fn rank(requirement: &PaymentRequirements) -> Option<(u8, PaymentChain)> { + match (requirement.scheme.as_str(), chain_of(&requirement.network)?) { + ("exact", PaymentChain::Solana) => Some((0, PaymentChain::Solana)), + ("exact", PaymentChain::Evm) => Some((1, PaymentChain::Evm)), + ("upto", PaymentChain::Evm) if is_payable_upto(requirement) => Some((2, PaymentChain::Evm)), + _ => None, + } +} + +/// The index and chain of the requirement to pay: the best-ranked payable +/// option (see `rank`), the first one of that rank on a tie. /// /// Options on networks or in assets outside the allowlist are skipped, so a -/// server that also offers a payable one is still paid. +/// server that also offers a payable one is still paid. With a `network` pin +/// (a CAIP-2 chain id such as `eip155:8453`, or a namespace such as `eip155`), +/// options on any other network are not considered at all. /// /// # Errors /// -/// [`X402Error::NoPaymentOption`] when the challenge has no `exact` option on a -/// Solana or EVM network at all; otherwise the refusal for the first such option -/// when none of them is payable. +/// [`X402Error::NoPaymentOptionOnNetwork`] when a pin leaves no option; +/// [`X402Error::NoPaymentOption`] when the challenge has no option this crate +/// can pay at all; otherwise the refusal for the first such option when none +/// of them is in an allowed network and asset. pub(crate) fn select_requirement( challenge: &PaymentRequired, + network: Option<&str>, ) -> Result<(usize, PaymentChain), X402Error> { let mut first_refusal = None; - let mut evm = None; + let mut best: Option<(u8, usize, PaymentChain)> = None; + let mut pinned_any = false; for (index, requirement) in challenge.accepts.iter().enumerate() { - let Some(chain) = chain_of(&requirement.network).filter(|_| requirement.scheme == "exact") - else { + if network.is_some_and(|pin| !matches_pin(&requirement.network, pin)) { + continue; + } + pinned_any = true; + let Some((rank, chain)) = rank(requirement) else { continue; }; match ensure_payable(requirement) { - Ok(()) if chain == PaymentChain::Solana => return Ok((index, chain)), - Ok(()) => { - evm.get_or_insert((index, chain)); + Ok(()) if best.is_none_or(|(best_rank, _, _)| rank < best_rank) => { + best = Some((rank, index, chain)); } + Ok(()) => {} Err(refusal) => { first_refusal.get_or_insert(refusal); } } } - match (evm, first_refusal) { - (Some(choice), _) => Ok(choice), - (None, Some(refusal)) => Err(refusal), - (None, None) => Err(X402Error::NoPaymentOption), + match (best, first_refusal, network) { + (Some((_, index, chain)), _, _) => Ok((index, chain)), + (None, Some(refusal), _) => Err(refusal), + (None, None, Some(pin)) if !pinned_any => Err(X402Error::NoPaymentOptionOnNetwork { + network: pin.to_string(), + }), + (None, None, _) => Err(X402Error::NoPaymentOption), } } + +#[cfg(test)] +#[path = "select_tests.rs"] +mod tests; diff --git a/crates/tinywallet-x402/src/protocol/select_tests.rs b/crates/tinywallet-x402/src/protocol/select_tests.rs new file mode 100644 index 00000000..d59c80ea --- /dev/null +++ b/crates/tinywallet-x402/src/protocol/select_tests.rs @@ -0,0 +1,130 @@ +//! Tests for choosing the requirement to pay: which `upto` options are +//! payable, how they rank against `exact`, and the caller's network pin. + +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use super::*; +use crate::test_support::{challenge, evm_requirement, solana_requirement}; +use crate::wire::{BASE_MAINNET_CAIP2, PaymentExtra}; + +const TWITR_UPTO: &str = include_str!("../wire/fixtures/twitr-upto-challenge.json"); +const FACILITATOR: &str = "0x4c934c63C786157Fefd990945b25eA60a0FB0205"; + +fn upto_requirement(method: Option<&str>, facilitator: Option<&str>) -> PaymentRequirements { + let mut requirement = evm_requirement(); + requirement.scheme = "upto".into(); + requirement.extra = Some(PaymentExtra { + name: Some("USD Coin".into()), + version: Some("2".into()), + asset_transfer_method: method.map(Into::into), + facilitator_address: facilitator.map(Into::into), + ..PaymentExtra::default() + }); + requirement +} + +fn pick(accepts: Vec) -> Result<(usize, PaymentChain), X402Error> { + select_requirement(&challenge(accepts), None) +} + +#[test] +fn the_twitr_volume_challenge_selects_its_upto_option() { + let twitr: PaymentRequired = serde_json::from_str(TWITR_UPTO).unwrap(); + assert_eq!( + select_requirement(&twitr, None).unwrap(), + (0, PaymentChain::Evm) + ); +} + +#[test] +fn a_permit2_upto_option_is_payable() { + let upto = upto_requirement(Some("permit2"), Some(FACILITATOR)); + assert_eq!(pick(vec![upto]).unwrap(), (0, PaymentChain::Evm)); +} + +#[test] +fn an_upto_option_without_a_transfer_method_defaults_to_permit2() { + let upto = upto_requirement(None, Some(FACILITATOR)); + assert_eq!(pick(vec![upto]).unwrap(), (0, PaymentChain::Evm)); +} + +#[test] +fn exact_is_preferred_over_upto_whatever_the_order() { + let upto = upto_requirement(Some("permit2"), Some(FACILITATOR)); + assert_eq!( + pick(vec![upto.clone(), evm_requirement()]).unwrap(), + (1, PaymentChain::Evm) + ); + assert_eq!( + pick(vec![upto, solana_requirement()]).unwrap(), + (1, PaymentChain::Solana) + ); +} + +#[test] +fn a_malformed_upto_option_is_never_selected() { + let refused = [ + upto_requirement(Some("permit2"), None), + upto_requirement(Some("permit2"), Some("0xnot-an-address")), + upto_requirement(Some("eip3009"), Some(FACILITATOR)), + { + let mut no_extra = upto_requirement(None, Some(FACILITATOR)); + no_extra.extra = None; + no_extra + }, + { + let mut on_solana = solana_requirement(); + on_solana.scheme = "upto".into(); + on_solana + }, + ]; + for requirement in refused { + assert!( + matches!( + pick(vec![requirement.clone()]), + Err(X402Error::NoPaymentOption) + ), + "{requirement:?} must not be selectable" + ); + } +} + +#[test] +fn an_upto_option_in_the_wrong_asset_is_refused_by_the_allowlist() { + let mut upto = upto_requirement(Some("permit2"), Some(FACILITATOR)); + upto.asset = "0x1111111111111111111111111111111111111111".into(); + assert!(matches!( + pick(vec![upto]), + Err(X402Error::UnsupportedAsset { .. }) + )); +} + +#[test] +fn a_network_pin_selects_only_matching_options() { + let accepts = vec![solana_requirement(), evm_requirement()]; + let both = challenge(accepts); + assert_eq!( + select_requirement(&both, Some(BASE_MAINNET_CAIP2)).unwrap(), + (1, PaymentChain::Evm) + ); + assert_eq!( + select_requirement(&both, Some("eip155")).unwrap(), + (1, PaymentChain::Evm) + ); + assert_eq!( + select_requirement(&both, Some("solana")).unwrap(), + (0, PaymentChain::Solana) + ); +} + +#[test] +fn a_network_pin_with_no_match_is_refused() { + let solana_only = challenge(vec![solana_requirement()]); + for pin in ["eip155", BASE_MAINNET_CAIP2, "eip155:84532", "eip"] { + let error = select_requirement(&solana_only, Some(pin)).unwrap_err(); + assert!( + matches!(&error, X402Error::NoPaymentOptionOnNetwork { network } if network == pin), + "{pin}: {error:?}" + ); + } +} diff --git a/crates/tinywallet-x402/src/test_support/mod.rs b/crates/tinywallet-x402/src/test_support/mod.rs index 6f1646f2..1b7dd3e8 100644 --- a/crates/tinywallet-x402/src/test_support/mod.rs +++ b/crates/tinywallet-x402/src/test_support/mod.rs @@ -240,7 +240,11 @@ pub(crate) fn evm_requirement() -> PaymentRequirements { memo: None, name: Some("USD Coin".into()), version: Some("2".into()), + asset_transfer_method: None, + facilitator_address: None, + other: serde_json::Map::new(), }), + other: serde_json::Map::new(), } } @@ -258,7 +262,11 @@ pub(crate) fn solana_requirement() -> PaymentRequirements { memo: Some("pi_3abc123".into()), name: None, version: None, + asset_transfer_method: None, + facilitator_address: None, + other: serde_json::Map::new(), }), + other: serde_json::Map::new(), } } diff --git a/crates/tinywallet-x402/src/tools/mod_settle_tests.rs b/crates/tinywallet-x402/src/tools/mod_settle_tests.rs index a6dadae7..2de9fb49 100644 --- a/crates/tinywallet-x402/src/tools/mod_settle_tests.rs +++ b/crates/tinywallet-x402/src/tools/mod_settle_tests.rs @@ -45,3 +45,82 @@ async fn a_receipt_for_another_network_or_amount_does_not_settle_the_payment() { ledger::reset_global(); } } + +fn upto_receipt(amount: &str, transaction: &str) -> String { + B64.encode( + serde_json::to_vec(&SettlementResponse { + success: true, + transaction: transaction.into(), + network: "eip155:8453".into(), + payer: None, + error_reason: None, + amount: Some(amount.into()), + extensions: serde_json::Map::new(), + }) + .unwrap(), + ) +} + +#[tokio::test] +async fn an_upto_payment_is_recorded_at_the_amount_actually_charged() { + let _guard = ledger::TEST_LOCK.lock().await; + let twitr: crate::wire::PaymentRequired = + serde_json::from_str(include_str!("../wire/fixtures/twitr-upto-challenge.json")).unwrap(); + for (charged, transaction, display) in [ + ("1200", "0xsettled", "0.001200 USDC"), + ("0", "", "0.000000 USDC"), + ] { + let _dir = init_ledger(); + let server = TestServer::start(ServerConfig { + receipt: Some(upto_receipt(charged, transaction)), + ..paid_config(twitr.accepts[0].clone()) + }) + .await; + let result = run(&tool(), json!({"url": server.url})).await; + assert!(!result.is_error, "{}", text(&result)); + assert!(text(&result).contains(display), "{}", text(&result)); + + let records = records(); + let pending = records.first().unwrap(); + assert_eq!(pending.status, PaymentStatus::Pending); + assert_eq!( + pending.amount_atomic, 3600, + "the ceiling is held until settled" + ); + assert_eq!(pending.scheme.as_deref(), Some("upto")); + let settled = records.last().unwrap(); + assert_eq!(settled.status, PaymentStatus::Settled); + assert_eq!(settled.amount_atomic, charged.parse::().unwrap()); + assert_eq!(settled.amount_display, display); + assert_eq!(settled.scheme.as_deref(), Some("upto")); + assert_eq!( + settled.tx_signature.as_deref(), + Some(transaction).filter(|t| !t.is_empty()) + ); + assert_eq!( + ledger::with_ledger(ledger::PaymentLedger::outstanding_atomic).unwrap(), + 0, + "nothing of the ceiling stays held" + ); + ledger::reset_global(); + } +} + +#[tokio::test] +async fn an_upto_receipt_above_the_ceiling_keeps_the_ceiling_pending() { + let _guard = ledger::TEST_LOCK.lock().await; + let twitr: crate::wire::PaymentRequired = + serde_json::from_str(include_str!("../wire/fixtures/twitr-upto-challenge.json")).unwrap(); + let _dir = init_ledger(); + let server = TestServer::start(ServerConfig { + receipt: Some(upto_receipt("3601", "0xover")), + ..paid_config(twitr.accepts[0].clone()) + }) + .await; + let result = run(&tool(), json!({"url": server.url})).await; + assert!(!result.is_error, "{}", text(&result)); + let last = records().pop().unwrap(); + assert_eq!(last.status, PaymentStatus::Pending); + assert_eq!(last.amount_atomic, 3600); + ledger::reset_global(); +} diff --git a/crates/tinywallet-x402/src/tools/request.rs b/crates/tinywallet-x402/src/tools/request.rs index 81ac45ba..7af22a19 100644 --- a/crates/tinywallet-x402/src/tools/request.rs +++ b/crates/tinywallet-x402/src/tools/request.rs @@ -13,7 +13,7 @@ use tinywallet_crypto::rpc::Transport; use crate::crypto::{CryptoPayments, PaymentSigner}; use crate::ledger::{self, PaymentRecord, PaymentStatus}; -use crate::protocol::{PaymentBuilder, ProxyPolicy, handle_402_and_pay, settles}; +use crate::protocol::{PaymentBuilder, ProxyPolicy, handle_402_and_pay, settled_amount}; use crate::thread::{NoThread, ThreadScope}; use crate::wire::{ BASE_MAINNET_CAIP2, BASE_SEPOLIA_CAIP2, ETHEREUM_MAINNET_CAIP2, HEADER_PAYMENT_REQUIRED, @@ -328,26 +328,31 @@ impl X402RequestTool { // Record the pending payment. Every later state is a new line with the // same id. let record_id = uuid::Uuid::new_v4().to_string(); - let record = |status: PaymentStatus, tx_signature: Option| PaymentRecord { - id: record_id.clone(), - url: url.clone(), - asset: payment.asset.clone(), - amount_atomic: payment.amount_atomic, - amount_display: amount_display.clone(), - recipient: payment.recipient.clone(), - network: payment.network.clone(), - tx_signature, - status, - timestamp: chrono::Utc::now(), - authorization_valid_until: payment.authorization_valid_until, - solana_last_valid_block_height: payment.solana_last_valid_block_height, - authorization_expired_at: None, - authorization_expiry_observed_height: None, - session_id: session_id.clone(), - thread_id: thread_id.clone(), + // An `upto` payment holds its signed ceiling while pending and is + // recorded at what the receipt says was charged once it settles. + let record = |status: PaymentStatus, tx_signature: Option, amount_atomic: u64| { + PaymentRecord { + id: record_id.clone(), + url: url.clone(), + asset: payment.asset.clone(), + amount_atomic, + amount_display: format_usdc(amount_atomic), + recipient: payment.recipient.clone(), + network: payment.network.clone(), + tx_signature, + status, + timestamp: chrono::Utc::now(), + authorization_valid_until: payment.authorization_valid_until, + solana_last_valid_block_height: payment.solana_last_valid_block_height, + authorization_expired_at: None, + authorization_expiry_observed_height: None, + session_id: session_id.clone(), + thread_id: thread_id.clone(), + scheme: Some(payment.scheme.clone()), + } }; if reservation - .commit_durable(record(PaymentStatus::Pending, None)) + .commit_durable(record(PaymentStatus::Pending, None, payment.amount_atomic)) .is_err() { return ToolResult::error( @@ -370,26 +375,28 @@ impl X402RequestTool { }; // Step 5: read the settlement response and update the ledger. - let receipt = paid_response - .headers() - .get(HEADER_PAYMENT_RESPONSE) - .and_then(|v| v.to_str().ok()) - .and_then(|b64| B64.decode(b64).ok()) - .and_then(|bytes| serde_json::from_slice::(&bytes).ok()) - .filter(|receipt| settles(receipt, &payment.network, payment.amount_atomic)); + let receipt = settlement_receipt( + &paid_response, + &payment.network, + &payment.scheme, + payment.amount_atomic, + ); + // An error response or elapsed authorization deadline does not prove + // that a proof returned to the server did not settle: no receipt keeps + // the payment pending at the amount signed for. let settled_status = if receipt.is_some() { PaymentStatus::Settled } else { - // An error response or elapsed authorization deadline does not - // prove that a proof returned to the server did not settle. PaymentStatus::Pending }; - let tx_sig = receipt - .filter(|receipt| !receipt.transaction.is_empty()) - .map(|receipt| receipt.transaction); + let (charged_atomic, tx_sig) = receipt + .map_or((payment.amount_atomic, None), |(r, charged)| { + (charged, Some(r.transaction).filter(|tx| !tx.is_empty())) + }); + let amount_display = format_usdc(charged_atomic); if settled_status != PaymentStatus::Pending && ledger::with_ledger_mut(|ledger| { - ledger.try_record_payment(record(settled_status, tx_sig.clone())) + ledger.try_record_payment(record(settled_status, tx_sig.clone(), charged_atomic)) }) .and_then(|result| result) .is_err() @@ -418,6 +425,25 @@ impl X402RequestTool { } } +/// The receipt on `response` and the amount it says the payment signed for +/// `signed_atomic` under `scheme` was charged, when it settles that payment +/// (see [`settled_amount`]). +fn settlement_receipt( + response: &reqwest::Response, + network: &str, + scheme: &str, + signed_atomic: u64, +) -> Option<(SettlementResponse, u64)> { + let receipt = response + .headers() + .get(HEADER_PAYMENT_RESPONSE) + .and_then(|v| v.to_str().ok()) + .and_then(|b64| B64.decode(b64).ok()) + .and_then(|bytes| serde_json::from_slice::(&bytes).ok())?; + let charged = settled_amount(&receipt, network, Some(scheme), signed_atomic)?; + Some((receipt, charged)) +} + /// Format an amount for the tool's human-readable response. pub(super) fn format_usdc(amount_atomic: u64) -> String { crate::ledger::format_usdc(amount_atomic) diff --git a/crates/tinywallet-x402/src/wire/fixtures/README.md b/crates/tinywallet-x402/src/wire/fixtures/README.md new file mode 100644 index 00000000..d2ff33f2 --- /dev/null +++ b/crates/tinywallet-x402/src/wire/fixtures/README.md @@ -0,0 +1,26 @@ +# Live x402 challenge fixtures + +Decoded `PAYMENT-REQUIRED` headers captured from twitr.sh on 2026-11-12. Both +requests are free: a 402 is answered before anything is paid or signed. + +- `twitr-upto-challenge.json` — the volume tool challenge. It offers only the + `upto` scheme on Base, with Permit2 `extra` fields, a per-requirement + `extensions` object and the top-level `eip2612GasSponsoring` declaration. + + ```sh + curl -s -D - -o /dev/null -X POST https://twitr.sh/api/tools/x_search \ + -H 'content-type: application/json' -d '{"resultsLimit":3,"query":"x"}' \ + | grep -i ^payment-required | cut -d' ' -f2- | tr -d '\r' | base64 -d + ``` + +- `twitr-siwx-challenge.json` — the account-linking challenge. `accepts` is + empty; the server asks only for the `sign-in-with-x` extension. + + ```sh + curl -s -i -X POST https://twitr.sh/api/x-accounts/start \ + -H 'content-type: application/json' -d '{"username":"x"}' \ + | grep -i ^payment-required | cut -d' ' -f2- | tr -d '\r' | base64 -d + ``` + +The SIWX fixture's `expirationTime` is in the past by the time tests run, so +tests that sign it pass an explicit clock inside its validity window. diff --git a/crates/tinywallet-x402/src/wire/fixtures/twitr-siwx-challenge.json b/crates/tinywallet-x402/src/wire/fixtures/twitr-siwx-challenge.json new file mode 100644 index 00000000..7cab202b --- /dev/null +++ b/crates/tinywallet-x402/src/wire/fixtures/twitr-siwx-challenge.json @@ -0,0 +1,103 @@ +{ + "x402Version": 2, + "error": "SIWX authentication required", + "resource": { + "url": "https://twitr.sh/api/x-accounts/start", + "description": "Sign in to connect an account", + "mimeType": "application/json" + }, + "accepts": [], + "extensions": { + "sign-in-with-x": { + "info": { + "domain": "twitr.sh", + "uri": "https://twitr.sh/api/x-accounts/start", + "version": "1", + "nonce": "c3dae5e13c973fa183371bf7fa769206", + "issuedAt": "2026-11-12T19:40:12.348Z", + "resources": [ + "https://twitr.sh/api/x-accounts/start" + ], + "expirationTime": "2026-11-12T19:45:12.348Z", + "statement": "Sign in to connect an account" + }, + "supportedChains": [ + { + "chainId": "eip155:8453", + "type": "eip191" + }, + { + "chainId": "eip155:84532", + "type": "eip191" + } + ], + "schema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "domain": { + "type": "string" + }, + "address": { + "type": "string" + }, + "statement": { + "type": "string" + }, + "uri": { + "type": "string", + "format": "uri" + }, + "version": { + "type": "string" + }, + "chainId": { + "type": "string" + }, + "type": { + "type": "string" + }, + "nonce": { + "type": "string" + }, + "issuedAt": { + "type": "string", + "format": "date-time" + }, + "expirationTime": { + "type": "string", + "format": "date-time" + }, + "notBefore": { + "type": "string", + "format": "date-time" + }, + "requestId": { + "type": "string" + }, + "resources": { + "type": "array", + "items": { + "type": "string", + "format": "uri" + } + }, + "signature": { + "type": "string" + } + }, + "required": [ + "domain", + "address", + "uri", + "version", + "chainId", + "type", + "nonce", + "issuedAt", + "signature" + ] + } + } + } +} diff --git a/crates/tinywallet-x402/src/wire/fixtures/twitr-upto-challenge.json b/crates/tinywallet-x402/src/wire/fixtures/twitr-upto-challenge.json new file mode 100644 index 00000000..d453fe85 --- /dev/null +++ b/crates/tinywallet-x402/src/wire/fixtures/twitr-upto-challenge.json @@ -0,0 +1,378 @@ +{ + "x402Version": 2, + "error": "payment_required", + "resource": { + "url": "https://twitr.sh/api/tools/x_search", + "description": "Search X/Twitter tweets with the full operator set — keyword, exact phrase, from-user, language, date range, media type, minimum likes/retweets, verified-only — or search user profiles by keyword. Billed per tweet returned against your resultsLimit cap. Built for tracking what people say about a topic, brand, or ticker in real time.", + "mimeType": "application/json" + }, + "accepts": [ + { + "scheme": "upto", + "network": "eip155:8453", + "asset": "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913", + "amount": "3600", + "payTo": "0xb5194A98DbDBb7028B585Db26B972e7F0F3f826A", + "maxTimeoutSeconds": 300, + "extra": { + "name": "USD Coin", + "version": "2", + "assetTransferMethod": "permit2", + "facilitatorAddress": "0x4c934c63C786157Fefd990945b25eA60a0FB0205" + }, + "extensions": { + "eip2612GasSponsoring": { + "info": { + "description": "The facilitator accepts EIP-2612 gasless Permit to `Permit2` canonical contract.", + "version": "1" + }, + "schema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "from": { + "type": "string", + "pattern": "^0x[a-fA-F0-9]{40}$", + "description": "The address of the sender." + }, + "asset": { + "type": "string", + "pattern": "^0x[a-fA-F0-9]{40}$", + "description": "The address of the ERC-20 token contract." + }, + "spender": { + "type": "string", + "pattern": "^0x[a-fA-F0-9]{40}$", + "description": "The address of the spender (Canonical Permit2)." + }, + "amount": { + "type": "string", + "pattern": "^[0-9]+$", + "description": "The amount to approve (uint256). Typically MaxUint." + }, + "nonce": { + "type": "string", + "pattern": "^[0-9]+$", + "description": "The current nonce of the sender." + }, + "deadline": { + "type": "string", + "pattern": "^[0-9]+$", + "description": "The timestamp at which the signature expires." + }, + "signature": { + "type": "string", + "pattern": "^0x[a-fA-F0-9]+$", + "description": "The 65-byte concatenated signature (r, s, v) as a hex string." + }, + "version": { + "type": "string", + "pattern": "^[0-9]+(\\.[0-9]+)*$", + "description": "Schema version identifier." + } + }, + "required": [ + "from", + "asset", + "spender", + "amount", + "nonce", + "deadline", + "signature", + "version" + ] + } + } + } + } + ], + "extensions": { + "bazaar": { + "info": { + "input": { + "type": "http", + "bodyType": "json", + "body": { + "q": "artificial intelligence", + "type": "search-tweets", + "resultsLimit": 50, + "language": "en", + "minFaves": 100 + }, + "method": "POST" + }, + "output": { + "type": "json", + "example": { + "items": [ + { + "id": "1893710452812718080", + "text": "This is a great thread, thanks for sharing.", + "authorUsername": "elonmusk", + "likeCount": 1180, + "createdAt": "2026-02-24T10:05:00.000Z" + } + ], + "runId": "tw_example", + "duration": 2, + "payment": { + "protocol": "x402", + "amount": "0.060000", + "currency": "USD" + } + } + } + }, + "schema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "input": { + "type": "object", + "properties": { + "type": { + "type": "string", + "const": "http" + }, + "method": { + "type": "string", + "enum": [ + "POST", + "PUT", + "PATCH" + ] + }, + "bodyType": { + "type": "string", + "enum": [ + "json", + "form-data", + "text" + ] + }, + "body": { + "type": "object", + "properties": { + "type": { + "type": "string", + "enum": [ + "search-tweets", + "search-users" + ], + "description": "Search tweets (default) or users." + }, + "q": { + "type": "string", + "description": "Search query (X operator syntax supported for tweets)." + }, + "resultsLimit": { + "type": "integer", + "minimum": 1, + "maximum": 10000, + "description": "search-tweets: MANDATORY max tweets returned, billed per tweet." + }, + "cursor": { + "type": "string", + "description": "search-users: pagination cursor from a previous call's report.next_cursor." + }, + "fromUser": { + "type": "string" + }, + "language": { + "type": "string" + }, + "sinceDate": { + "type": "string", + "description": "YYYY-MM-DD" + }, + "untilDate": { + "type": "string", + "description": "YYYY-MM-DD" + }, + "mediaType": { + "type": "string", + "enum": [ + "images", + "videos", + "gifs", + "media" + ] + }, + "minFaves": { + "type": "integer" + }, + "minRetweets": { + "type": "integer" + }, + "minReplies": { + "type": "integer" + }, + "verifiedOnly": { + "type": "boolean" + }, + "exactPhrase": { + "type": "string" + }, + "excludeWords": { + "type": "string" + }, + "advancedQuery": { + "type": "string", + "description": "Raw X search operator string appended to q." + } + }, + "required": [ + "q" + ], + "allOf": [ + { + "if": { + "properties": { + "type": { + "const": "search-users" + } + } + }, + "then": {}, + "else": { + "required": [ + "resultsLimit" + ] + } + } + ] + } + }, + "required": [ + "type", + "method", + "bodyType", + "body" + ], + "additionalProperties": false + }, + "output": { + "type": "object", + "properties": { + "type": { + "type": "string" + }, + "example": { + "type": "object", + "properties": { + "items": { + "type": "array", + "description": "Returned items. Shape varies per tool — see each tool's outputSample for a concrete example.", + "items": { + "type": "object" + } + }, + "runId": { + "type": "string", + "description": "Run ID for debugging/audit." + }, + "duration": { + "type": "integer", + "description": "Run duration in seconds." + }, + "payment": { + "type": "object", + "description": "Settlement summary (protocol, amount, currency)." + } + }, + "required": [ + "items" + ] + } + }, + "required": [ + "type" + ] + } + }, + "required": [ + "input" + ] + }, + "discoverable": true, + "category": "api", + "tags": [ + "twitter", + "x", + "search", + "tweets", + "keyword", + "hashtag", + "query", + "social-listening", + "brand-monitoring", + "sentiment", + "user-search", + "agent", + "x402" + ] + }, + "eip2612GasSponsoring": { + "info": { + "description": "The facilitator accepts EIP-2612 gasless Permit to `Permit2` canonical contract.", + "version": "1" + }, + "schema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "from": { + "type": "string", + "pattern": "^0x[a-fA-F0-9]{40}$", + "description": "The address of the sender." + }, + "asset": { + "type": "string", + "pattern": "^0x[a-fA-F0-9]{40}$", + "description": "The address of the ERC-20 token contract." + }, + "spender": { + "type": "string", + "pattern": "^0x[a-fA-F0-9]{40}$", + "description": "The address of the spender (Canonical Permit2)." + }, + "amount": { + "type": "string", + "pattern": "^[0-9]+$", + "description": "The amount to approve (uint256). Typically MaxUint." + }, + "nonce": { + "type": "string", + "pattern": "^[0-9]+$", + "description": "The current nonce of the sender." + }, + "deadline": { + "type": "string", + "pattern": "^[0-9]+$", + "description": "The timestamp at which the signature expires." + }, + "signature": { + "type": "string", + "pattern": "^0x[a-fA-F0-9]+$", + "description": "The 65-byte concatenated signature (r, s, v) as a hex string." + }, + "version": { + "type": "string", + "pattern": "^[0-9]+(\\.[0-9]+)*$", + "description": "Schema version identifier." + } + }, + "required": [ + "from", + "asset", + "spender", + "amount", + "nonce", + "deadline", + "signature", + "version" + ] + } + } + } +} diff --git a/crates/tinywallet-x402/src/wire/mod.rs b/crates/tinywallet-x402/src/wire/mod.rs index c6de1069..3b7d7134 100644 --- a/crates/tinywallet-x402/src/wire/mod.rs +++ b/crates/tinywallet-x402/src/wire/mod.rs @@ -39,18 +39,24 @@ //! [CAIP-2]: https://chainagnostic.org/CAIPs/caip-2 mod assets; +mod siwx; #[cfg(test)] #[path = "mod_tests.rs"] mod test; mod types; pub use assets::{AssetCheck, SUPPORTED_USDC, check_usdc}; +pub use siwx::{ + HEADER_SIGN_IN_WITH_X, SIGN_IN_WITH_X, SiwxExtension, SiwxInfo, SiwxPayload, SiwxSupportedChain, +}; pub use types::{ - BASE_MAINNET_CAIP2, BASE_SEPOLIA_CAIP2, COMPUTE_BUDGET_PROGRAM, ETHEREUM_MAINNET_CAIP2, - EvmAuthorization, EvmPaymentProof, HEADER_PAYMENT_REQUIRED, HEADER_PAYMENT_REQUIRED_V1, - HEADER_PAYMENT_RESPONSE, HEADER_PAYMENT_SIGNATURE, HEADER_PAYMENT_SIGNATURE_V1, PaymentChain, - PaymentExtra, PaymentPayload, PaymentProof, PaymentRequired, PaymentRequirements, ResourceInfo, - SOLANA_DEVNET_CAIP2, SOLANA_MAINNET_CAIP2, SPL_MEMO_PROGRAM, SPL_TOKEN_PROGRAM, - SettlementResponse, SolanaPaymentProof, USDC_BASE_MAINNET, USDC_BASE_SEPOLIA, - USDC_ETHEREUM_MAINNET, USDC_MINT_DEVNET, USDC_MINT_MAINNET, X402_VERSION, + BASE_MAINNET_CAIP2, BASE_SEPOLIA_CAIP2, COMPUTE_BUDGET_PROGRAM, EIP2612_GAS_SPONSORING, + ETHEREUM_MAINNET_CAIP2, EvmAuthorization, EvmPaymentProof, HEADER_PAYMENT_REQUIRED, + HEADER_PAYMENT_REQUIRED_V1, HEADER_PAYMENT_RESPONSE, HEADER_PAYMENT_SIGNATURE, + HEADER_PAYMENT_SIGNATURE_V1, PERMIT2_ADDRESS, PaymentChain, PaymentExtra, PaymentPayload, + PaymentProof, PaymentRequired, PaymentRequirements, Permit2Authorization, Permit2PaymentProof, + ResourceInfo, SOLANA_DEVNET_CAIP2, SOLANA_MAINNET_CAIP2, SPL_MEMO_PROGRAM, SPL_TOKEN_PROGRAM, + SettlementResponse, SolanaPaymentProof, TokenPermissions, UPTO_PERMIT2_PROXY_ADDRESS, + USDC_BASE_MAINNET, USDC_BASE_SEPOLIA, USDC_ETHEREUM_MAINNET, USDC_MINT_DEVNET, + USDC_MINT_MAINNET, UptoWitness, X402_VERSION, }; diff --git a/crates/tinywallet-x402/src/wire/mod_tests.rs b/crates/tinywallet-x402/src/wire/mod_tests.rs index d2534a95..fc0edc4d 100644 --- a/crates/tinywallet-x402/src/wire/mod_tests.rs +++ b/crates/tinywallet-x402/src/wire/mod_tests.rs @@ -22,6 +22,7 @@ fn requirement(network: &str, asset: &str, extra: Option) -> Payme pay_to: "Recipient".to_string(), max_timeout_seconds: 60, extra, + other: serde_json::Map::new(), } } @@ -53,6 +54,9 @@ fn a_challenge_with_extras_round_trips() { memo: Some("pi_3abc123".to_string()), name: None, version: None, + asset_transfer_method: None, + facilitator_address: None, + other: serde_json::Map::new(), }), )], extensions: serde_json::Map::new(), @@ -87,6 +91,9 @@ fn extra_accessors_return_the_server_supplied_values() { memo: Some("order_456".to_string()), name: None, version: None, + asset_transfer_method: None, + facilitator_address: None, + other: serde_json::Map::new(), }), ); assert_eq!(req.fee_payer_pubkey(), Some("FeePayer123")); @@ -107,6 +114,9 @@ fn extra_accessors_are_none_when_the_server_sent_no_extras() { memo: None, name: Some("USD Coin".to_string()), version: Some("2".to_string()), + asset_transfer_method: None, + facilitator_address: None, + other: serde_json::Map::new(), }), ); assert_eq!(partial.fee_payer_pubkey(), None); diff --git a/crates/tinywallet-x402/src/wire/siwx.rs b/crates/tinywallet-x402/src/wire/siwx.rs new file mode 100644 index 00000000..4facbc15 --- /dev/null +++ b/crates/tinywallet-x402/src/wire/siwx.rs @@ -0,0 +1,109 @@ +//! Wire types for the x402 `sign-in-with-x` extension (CAIP-122). +//! +//! A server that needs to know *who* is calling, rather than to be paid, +//! answers 402 with this extension in `PAYMENT-REQUIRED.extensions`. The client +//! signs the described sign-in message and retries with the +//! `SIGN-IN-WITH-X` header: base64 of a [`SiwxPayload`]. + +use serde::{Deserialize, Serialize}; + +/// The extension key in `PaymentRequired.extensions`. +pub const SIGN_IN_WITH_X: &str = "sign-in-with-x"; + +/// The request header carrying the signed proof. +pub const HEADER_SIGN_IN_WITH_X: &str = "SIGN-IN-WITH-X"; + +/// The server's `sign-in-with-x` declaration. Its JSON `schema` is not read. +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct SiwxExtension { + /// The message fields the server issued. + pub info: SiwxInfo, + /// The chains, and signature types, the server verifies. + pub supported_chains: Vec, +} + +/// The message fields a server issues for one sign-in (EIP-4361 / CAIP-122). +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct SiwxInfo { + /// The host (and port) asking for the sign-in. + pub domain: String, + /// The resource the sign-in is for. + pub uri: String, + /// A human-readable statement shown with the message. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub statement: Option, + /// The message version; `"1"`. + pub version: String, + /// The server's single-use nonce. + pub nonce: String, + /// RFC 3339 issue time. + pub issued_at: String, + /// RFC 3339 time after which the signed message is void. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub expiration_time: Option, + /// RFC 3339 time before which the signed message is not valid. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub not_before: Option, + /// The server's request identifier. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub request_id: Option, + /// URIs the sign-in grants access to. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub resources: Option>, +} + +/// One chain a server accepts a sign-in from. +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct SiwxSupportedChain { + /// CAIP-2 chain id, such as `eip155:8453`. + pub chain_id: String, + /// The signature type: `eip191` for EVM accounts, `ed25519` for Solana. + #[serde(rename = "type")] + pub kind: String, + /// The verification scheme, when the server names one. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub signature_scheme: Option, +} + +/// The signed proof, sent base64-encoded in the `SIGN-IN-WITH-X` header. +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct SiwxPayload { + /// As issued. + pub domain: String, + /// The signing account, EIP-55 checksummed. + pub address: String, + /// As issued. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub statement: Option, + /// As issued. + pub uri: String, + /// As issued. + pub version: String, + /// The chosen CAIP-2 chain id. + pub chain_id: String, + /// The chosen signature type. + #[serde(rename = "type")] + pub kind: String, + /// As issued. + pub nonce: String, + /// As issued. + pub issued_at: String, + /// As issued. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub expiration_time: Option, + /// As issued. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub not_before: Option, + /// As issued. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub request_id: Option, + /// As issued. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub resources: Option>, + /// The `0x` hex signature over the sign-in message. + pub signature: String, +} diff --git a/crates/tinywallet-x402/src/wire/types.rs b/crates/tinywallet-x402/src/wire/types.rs index 4e274af4..b16166c1 100644 --- a/crates/tinywallet-x402/src/wire/types.rs +++ b/crates/tinywallet-x402/src/wire/types.rs @@ -48,6 +48,13 @@ pub const BASE_SEPOLIA_CAIP2: &str = "eip155:84532"; /// CAIP-2 identifier for Ethereum mainnet. pub const ETHEREUM_MAINNET_CAIP2: &str = "eip155:1"; +/// The canonical Permit2 contract, the same on every EVM chain. +pub const PERMIT2_ADDRESS: &str = "0x000000000022D473030F116dDEE9F6B43aC78BA3"; +/// The `x402UptoPermit2Proxy`, spender of every `upto` permit. +pub const UPTO_PERMIT2_PROXY_ADDRESS: &str = "0x4020A4f3b7b90ccA423B9fabCc0CE57C6C240002"; +/// The extension key a server uses to accept an EIP-2612 permit for Permit2. +pub const EIP2612_GAS_SPONSORING: &str = "eip2612GasSponsoring"; + /// USDC contract on Base mainnet. pub const USDC_BASE_MAINNET: &str = "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"; /// USDC contract on Base Sepolia. @@ -115,9 +122,17 @@ pub struct PaymentRequirements { #[serde(default, skip_serializing_if = "Option::is_none")] /// See the x402 v2 specification. pub extra: Option, + /// Every other field the server sent, such as a per-requirement + /// `extensions` object, kept verbatim. + /// + /// A v2 server compares the `accepted` requirement it gets back with the + /// one it advertised and refuses a payment whose terms differ, so a field + /// this crate does not model must still be echoed back unchanged. + #[serde(flatten)] + pub other: serde_json::Map, } -#[derive(Debug, Clone, Serialize, Deserialize)] +#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] /// Scheme-specific extras a server attaches to a requirement. pub struct PaymentExtra { @@ -137,6 +152,19 @@ pub struct PaymentExtra { #[serde(default, skip_serializing_if = "Option::is_none")] /// See the x402 v2 specification. pub version: Option, + /// How the payer authorizes the transfer (EVM). `"permit2"` for the + /// `upto` scheme, which allows no other method. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub asset_transfer_method: Option, + /// The facilitator allowed to settle an `upto` authorization (EVM). The + /// payer signs it into the Permit2 witness, so no other party can settle. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub facilitator_address: Option, + /// Every other `extra` field the server sent, kept verbatim so the + /// `accepted` echo still holds all of them. See + /// [`PaymentRequirements::other`]. + #[serde(flatten)] + pub other: serde_json::Map, } // --------------------------------------------------------------------------- @@ -174,6 +202,8 @@ pub enum PaymentProof { Solana(SolanaPaymentProof), /// An EVM EIP-3009 authorisation. Evm(EvmPaymentProof), + /// An EVM Permit2 authorisation, used by the `upto` scheme. + Permit2(Permit2PaymentProof), } /// Solana `exact` scheme payload — a partially-signed `VersionedTransaction` @@ -224,6 +254,59 @@ pub struct EvmAuthorization { pub nonce: String, } +/// EVM `upto` scheme payload: a Permit2 `PermitWitnessTransferFrom` signed by +/// the token holder, which lets the `x402UptoPermit2Proxy` move up to +/// `permitted.amount` to `witness.to` when `witness.facilitator` settles. +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Permit2PaymentProof { + /// The EIP-712 signature, `0x` + `r ‖ s ‖ v`. + pub signature: String, + /// The signed permit, in the shape the facilitator rebuilds it from. + pub permit2_authorization: Permit2Authorization, +} + +/// The Permit2 permit an `upto` payment signs. +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Permit2Authorization { + /// The token holder. + pub from: String, + /// The token and the maximum amount. + pub permitted: TokenPermissions, + /// The contract allowed to use the permit: the `x402UptoPermit2Proxy`. + pub spender: String, + /// Permit2's unordered nonce, as a decimal string. + pub nonce: String, + /// Unix time after which the permit is void, as a decimal string. + pub deadline: String, + /// What the proxy is bound to. + pub witness: UptoWitness, +} + +/// Permit2's `TokenPermissions`. +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct TokenPermissions { + /// The token contract. + pub token: String, + /// The most that may be moved, in atomic units, as a decimal string. + pub amount: String, +} + +/// The x402 `upto` witness. +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct UptoWitness { + /// The only recipient. + pub to: String, + /// The only facilitator that may settle. + pub facilitator: String, + /// Unix time before which the permit is not yet valid, as a decimal + /// string. + pub valid_after: String, +} + // --------------------------------------------------------------------------- // Settlement response — server → client (PAYMENT-RESPONSE header) // --------------------------------------------------------------------------- @@ -306,6 +389,20 @@ pub enum PaymentChain { Evm, } +impl PaymentProof { + /// The Unix second after which the signed authorization can no longer be + /// used: EIP-3009's `validBefore` or the Permit2 `deadline`. `None` for + /// Solana, whose expiry is a block height, and for an unreadable value. + #[must_use] + pub fn authorization_deadline_secs(&self) -> Option { + match self { + Self::Evm(proof) => proof.authorization.valid_before.parse().ok(), + Self::Permit2(proof) => proof.permit2_authorization.deadline.parse().ok(), + Self::Solana(_) => None, + } + } +} + impl PaymentRequirements { /// Whether this requirement targets Solana mainnet-beta. #[must_use] @@ -344,3 +441,11 @@ impl PaymentRequirements { #[cfg(test)] #[path = "types_test_tests.rs"] mod test; + +#[cfg(test)] +#[path = "types_passthrough_tests.rs"] +mod passthrough_test; + +#[cfg(test)] +#[path = "types_permit2_tests.rs"] +mod permit2_test; diff --git a/crates/tinywallet-x402/src/wire/types_passthrough_tests.rs b/crates/tinywallet-x402/src/wire/types_passthrough_tests.rs new file mode 100644 index 00000000..ebbe95ab --- /dev/null +++ b/crates/tinywallet-x402/src/wire/types_passthrough_tests.rs @@ -0,0 +1,54 @@ +//! Tests that a requirement survives the round trip into `accepted`. +//! +//! A v2 server matches the `accepted` requirement it gets back against what it +//! advertised: every field outside `extra` must be equal, and `extra` must still +//! hold every server field. A field this crate does not model therefore has to +//! be echoed back untouched, or the payment is refused as an unknown option. + +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use super::{PaymentRequired, PaymentRequirements}; + +const TWITR_UPTO: &str = include_str!("fixtures/twitr-upto-challenge.json"); + +fn twitr_upto() -> (PaymentRequired, serde_json::Value) { + let raw: serde_json::Value = serde_json::from_str(TWITR_UPTO).unwrap(); + (serde_json::from_value(raw.clone()).unwrap(), raw) +} + +#[test] +fn a_requirement_echoes_every_field_the_server_sent() { + let (challenge, raw) = twitr_upto(); + let echoed = serde_json::to_value(&challenge.accepts[0]).unwrap(); + assert_eq!(echoed, raw["accepts"][0]); +} + +#[test] +fn an_unmodelled_extra_field_round_trips() { + let requirement: PaymentRequirements = serde_json::from_value(serde_json::json!({ + "scheme": "exact", + "network": "eip155:8453", + "amount": "1", + "asset": "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913", + "payTo": "0xb5194A98DbDBb7028B585Db26B972e7F0F3f826A", + "maxTimeoutSeconds": 60, + "extra": {"name": "USD Coin", "version": "2", "somethingNew": {"nested": [1, 2]}}, + "topLevelNew": true + })) + .unwrap(); + let echoed = serde_json::to_value(&requirement).unwrap(); + assert_eq!(echoed["extra"]["somethingNew"]["nested"][1], 2); + assert_eq!(echoed["topLevelNew"], true); +} + +#[test] +fn the_upto_extra_fields_are_readable() { + let (challenge, _) = twitr_upto(); + let extra = challenge.accepts[0].extra.as_ref().unwrap(); + assert_eq!( + extra.facilitator_address.as_deref(), + Some("0x4c934c63C786157Fefd990945b25eA60a0FB0205") + ); + assert_eq!(extra.asset_transfer_method.as_deref(), Some("permit2")); + assert!(extra.other.is_empty()); +} diff --git a/crates/tinywallet-x402/src/wire/types_permit2_tests.rs b/crates/tinywallet-x402/src/wire/types_permit2_tests.rs new file mode 100644 index 00000000..3370c141 --- /dev/null +++ b/crates/tinywallet-x402/src/wire/types_permit2_tests.rs @@ -0,0 +1,62 @@ +//! Tests for the Permit2 (`upto`) proof's wire shape and the deadline every +//! EVM proof exposes. + +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use super::{EvmAuthorization, EvmPaymentProof, PaymentProof, SolanaPaymentProof}; + +/// The payload example of the x402 `upto` EVM specification, verbatim. +const SPEC_UPTO_PAYLOAD: &str = r#"{ + "signature": "0x2d6a7588d6acca505cbf0d9a4a227e0c52c6c34008c8e8986a1283259764173608a2ce6496642e377d6da8dbbf5836e9bd15092f9ecab05ded3d6293af148b571c", + "permit2Authorization": { + "permitted": {"token": "0x036CbD53842c5426634e7929541eC2318f3dCF7e", "amount": "5000000"}, + "from": "0x857b06519E91e3A54538791bDbb0E22373e36b66", + "spender": "0x4020A4f3b7b90ccA423B9fabCc0CE57C6C240002", + "nonce": "0xf3746613c2d920b5fdabc0856f2aeb2d4f88ee6037b8cc5d04a71a4462f13480", + "deadline": "1740672154", + "witness": { + "to": "0x209693Bc6afc0C5328bA36FaF03C514EF312287C", + "facilitator": "0xFacilitatorAddress1234567890123456789012", + "validAfter": "1740672089" + } + } +}"#; + +#[test] +fn the_spec_upto_payload_reads_as_a_permit2_proof_and_round_trips() { + let raw: serde_json::Value = serde_json::from_str(SPEC_UPTO_PAYLOAD).unwrap(); + let proof: PaymentProof = serde_json::from_value(raw.clone()).unwrap(); + let PaymentProof::Permit2(permit2) = &proof else { + panic!("expected a Permit2 proof, got {proof:?}"); + }; + assert_eq!( + permit2.permit2_authorization.witness.valid_after, + "1740672089" + ); + assert_eq!(serde_json::to_value(&proof).unwrap(), raw); +} + +#[test] +fn every_evm_proof_exposes_its_deadline() { + let raw: serde_json::Value = serde_json::from_str(SPEC_UPTO_PAYLOAD).unwrap(); + let permit2: PaymentProof = serde_json::from_value(raw).unwrap(); + assert_eq!(permit2.authorization_deadline_secs(), Some(1_740_672_154)); + + let eip3009 = PaymentProof::Evm(EvmPaymentProof { + signature: "0x".into(), + authorization: EvmAuthorization { + from: "f".into(), + to: "t".into(), + value: "1".into(), + valid_after: "0".into(), + valid_before: "1800000000".into(), + nonce: "0x".into(), + }, + }); + assert_eq!(eip3009.authorization_deadline_secs(), Some(1_800_000_000)); + + let solana = PaymentProof::Solana(SolanaPaymentProof { + transaction: "tx".into(), + }); + assert_eq!(solana.authorization_deadline_secs(), None); +} diff --git a/crates/tinywallet-x402/src/wire/types_test_tests.rs b/crates/tinywallet-x402/src/wire/types_test_tests.rs index 02c7a12a..632fa591 100644 --- a/crates/tinywallet-x402/src/wire/types_test_tests.rs +++ b/crates/tinywallet-x402/src/wire/types_test_tests.rs @@ -14,6 +14,7 @@ fn requirement(scheme: &str, network: &str) -> PaymentRequirements { pay_to: "11111111111111111111111111111111".to_string(), max_timeout_seconds: 60, extra: None, + other: serde_json::Map::new(), } } diff --git a/src/client/mod_tests.rs b/src/client/mod_tests.rs index 8e1684c5..9a13afa5 100644 --- a/src/client/mod_tests.rs +++ b/src/client/mod_tests.rs @@ -1153,3 +1153,18 @@ async fn tron_status_treats_a_missing_receipt_result_as_success() { super::TxState::Failed ); } + +#[tokio::test] +async fn btc_and_tron_status_report_a_reply_that_is_not_json() { + for (network, path) in [ + (Network::Btc, "tx/abc/status"), + (Network::Tron, "wallet/gettransactioninfobyid"), + ] { + let transport = RestScript::new(&[(path, "busy".to_string())]); + let error = super::status(&transport, network, "abc").await.unwrap_err(); + assert!( + error.to_string().contains("not JSON"), + "{network:?}: {error}" + ); + } +} diff --git a/src/key/btc.rs b/src/key/btc.rs index 6972ff53..c771b9ee 100644 --- a/src/key/btc.rs +++ b/src/key/btc.rs @@ -16,7 +16,7 @@ use ripemd::Ripemd160; use sha2::{Digest, Sha256}; -use super::{DerivedKey, Error, Result, bip32, seed_from_mnemonic}; +use super::{DerivedKey, Result, bip32, derivation_failed, seed_from_mnemonic}; use crate::address::btc::encode_p2wpkh; use crate::chain::Chain; @@ -28,10 +28,8 @@ pub(super) fn derive(mnemonic: &str, path: &str) -> Result { // The *compressed* encoding: a P2WPKH witness program is defined over it, // and hashing the uncompressed form instead produces a valid-looking // address for an account holding no funds. - let address = - encode_p2wpkh(&hash160(&key.compressed_public())).map_err(|_| Error::Derivation { - step: "BTC P2WPKH address", - })?; + let address = encode_p2wpkh(&hash160(&key.compressed_public())) + .map_err(derivation_failed("BTC P2WPKH address"))?; Ok(DerivedKey::new( Chain::Btc, diff --git a/src/key/mod.rs b/src/key/mod.rs index 44e80615..1e51f0a7 100644 --- a/src/key/mod.rs +++ b/src/key/mod.rs @@ -288,6 +288,14 @@ pub fn mnemonic_seed(mnemonic: &str) -> Result>> { Ok(Zeroizing::new(seed.to_vec())) } +/// Maps a failure in a derivation step that cannot fail for a well-formed key +/// (an address encoding over bytes this module just built) to +/// [`Error::Derivation`], rather than unwrapping it: a panic in key derivation +/// would take a wallet down over an unreachable branch. +fn derivation_failed(step: &'static str) -> impl FnOnce(E) -> Error { + move |_| Error::Derivation { step } +} + fn seed_from_mnemonic(mnemonic: &str) -> Result>> { mnemonic_seed(mnemonic) } diff --git a/src/key/mod_tests.rs b/src/key/mod_tests.rs index f57df0d4..efecdfc3 100644 --- a/src/key/mod_tests.rs +++ b/src/key/mod_tests.rs @@ -12,7 +12,7 @@ #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] -use super::{Error, derive}; +use super::{Error, derivation_failed, derive}; use crate::chain::Chain; use std::fmt::Write as _; @@ -357,3 +357,31 @@ fn public_evm_address_matches_key_derivation_and_rejects_invalid_points() { "invalid SEC1 public key" ); } + +#[test] +fn a_seed_bip32_cannot_use_is_a_derivation_error() { + // BIP-32 master keys need a 16- to 64-byte seed. + let Err(error) = super::bip32::derive(&[7u8; 8], "m/44'/60'/0'/0/0") else { + panic!("an 8-byte seed derived a key"); + }; + assert!( + matches!( + error, + Error::Derivation { + step: "BIP-32 master key" + } + ), + "{error:?}" + ); +} + +#[test] +fn an_unreachable_step_failure_is_a_derivation_error_naming_the_step() { + let error = derivation_failed::<()>("BTC P2WPKH address")(()); + assert!(matches!( + error, + Error::Derivation { + step: "BTC P2WPKH address" + } + )); +} diff --git a/src/key/tron.rs b/src/key/tron.rs index 272e68c2..0885851b 100644 --- a/src/key/tron.rs +++ b/src/key/tron.rs @@ -8,7 +8,7 @@ use sha3::{Digest, Keccak256}; -use super::{DerivedKey, Error, Result, bip32, seed_from_mnemonic}; +use super::{DerivedKey, Result, bip32, derivation_failed, seed_from_mnemonic}; use crate::address::tron::{ADDRESS_BYTES, MAINNET_PREFIX}; use crate::chain::Chain; @@ -28,15 +28,12 @@ pub(super) fn derive(mnemonic: &str, path: &str) -> Result { /// last 20 bytes, prepend the Tron mainnet version byte, and base58check it. /// /// `encode` verifies the version byte and so returns a `Result`. It cannot -/// fail here — the prefix is written two lines above — but the error is mapped -/// rather than unwrapped, because a panic in key derivation would take a -/// wallet down over an unreachable branch. +/// fail here (the prefix is written two lines above), so the error is mapped +/// by [`derivation_failed`] rather than unwrapped. fn address_from_public(uncompressed: &[u8; 65]) -> Result { let hash = Keccak256::digest(&uncompressed[1..]); let mut bytes = [0u8; ADDRESS_BYTES]; bytes[0] = MAINNET_PREFIX; bytes[1..].copy_from_slice(&hash[12..]); - crate::address::tron::encode(&bytes).map_err(|_| Error::Derivation { - step: "Tron address encoding", - }) + crate::address::tron::encode(&bytes).map_err(derivation_failed("Tron address encoding")) }