The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
chore(web3): drop host-side wallet and x402 seam implementations
Steven Enamakel069f73b284ec
diff --git a/crates/openhuman-core/Cargo.toml b/crates/openhuman-core/Cargo.tomlindex 8b49c96170..b44efe2a1f 100644--- a/crates/openhuman-core/Cargo.toml+++ b/crates/openhuman-core/Cargo.toml@@ -497,32 +497,14 @@ tinyhosts-bus = { path = "../../vendor/tinyhosts/crates/tinyhosts-bus", optional# not pay for it. See the two-set note above `default`.## Taken as `tinywallet-bus`, the contract crate, and NOT the root `tinywallet`-# crate. The root crate is where key derivation, transaction building, signing-# and the chain clients live, and those are the gates that pull the `bitcoin`-# crate and its native secp256k1 build; all of it happens inside the loaded-# `tinywallet` module now, so this binary links none of it. What the contract-# crate carries is exactly what a host still runs itself: the wire types that-# cross the bus, the bus member names, address validation, the EIP-712 and ERC-20-# encoders the x402 payment path builds with, the `Transport` seam this crate-# implements, and the Tron verifier that checks what a node handed back before-# a transaction is sent for signing.+# crate. The host carries transport-neutral wire vocabulary only; wallet,+# Web3, x402 parsing, payment construction, signing, ABI encoding and ledger+# behavior execute inside the loaded TinyWallet module.## The root crate is still taken under [dev-dependencies], where test fixtures# derive a known account. Dev-dependency features are not linked into the# shipped binary, so that does not undo the shed.-tinywallet-bus = { path = "../../vendor/tinywallet/crates/tinywallet-bus", default-features = false, features = ["btc", "evm", "solana", "tron", "keccak", "net", "wire", "eip712", "abi", "tx-codec"], optional = true }-# Transitional adapter dependency: the pre-cutover host WalletEngine still-# consumes this leaf transport trait. It is removed with the direct engine path-# once every Wallet/Web3/x402 caller uses the module contract.-tinywallet-crypto = { path = "../../vendor/tinywallet/crates/tinywallet-crypto", default-features = false, features = ["net", "serde"], optional = true }-# The x402 payment flow (402 challenge, EVM/Solana payment builders, the-# spending ledger, the `x402_request` tool), moved out of `web3/x402`. The host-# keeps signing, proxy policy and RPC controllers and hands them in as seams.-tinywallet-x402 = { path = "../../vendor/tinywallet/crates/tinywallet-x402", default-features = false, features = ["wire", "pay", "ledger", "tools"], optional = true }-# The wallet engine and the swap/bridge/dapp service, moved out of `web3/`.-# The host implements its seams (signer, accounts, RPC endpoints, quote scope,-# backend) and keeps the controllers, keyring and consent.-tinywallet-web3 = { path = "../../vendor/tinywallet/crates/tinywallet-web3", default-features = false, features = ["tools"], optional = true }+tinywallet-bus = { path = "../../vendor/tinywallet/crates/tinywallet-bus", default-features = false, features = ["wire"], optional = true }[target.'cfg(windows)'.dependencies]@@ -756,31 +738,14 @@ voice = [# `voice::live`: live voice agent sessions over tinyagents-live."dep:tinyagents-live",]-# Web3 family: openhuman::web3 + web3::wallet + web3::x402 — the-# crypto wallet (multi-chain sign/broadcast), the high-level swap/bridge/dapp-# surface, and the x402 machine-payment protocol. Default-ON — the desktop app-# always ships with the wallet. Slim / headless builds opt out via-# `--no-default-features --features "<explicit list without web3>"`, which-# drops the exclusive `bitcoin` (P2WPKH PSBT) + `ethers-core` / `ethers-signers`-# / `coins-bip39` (EVM/mnemonic signing, used by the multi-chain wallet's EVM-# path) dependencies. Composes-# with the runtime `DomainSet::Web3` flag (#4796): the feature narrows the-# compile-time surface, `DomainSet` gates it at runtime.-# `k256` and `coins-bip39` are gone from this list: nothing in the shipped-# binary derives a key or signs with secp256k1 any more — the wallet module-# does both. `k256` is gone entirely; `coins-bip39` is gone entirely-# (the fixtures derive through `tinywallet`'s own copy).-#-# `curve25519-dalek` is gone from this list: the Solana off-curve check that-# derives an Associated Token Account is address arithmetic that now lives in-# `tinywallet-web3` (and `tinywallet-x402`), which own their own copy.+# Web3 family: product RPC/controllers, module adapters, and host-configured+# transport/custody/approval callbacks for Wallet, swaps, bridges, dapps, and+# x402. The algorithms and provider-specific state live in TinyWallet; this+# feature carries only the lightweight bus contract and generic HTTP client.web3 = ["dep:reqwest13","dep:webpki-roots","dep:tinywallet-bus",- "dep:tinywallet-crypto",- "dep:tinywallet-x402",- "dep:tinywallet-web3","modules",]diff --git a/crates/openhuman-core/src/web3/seams.rs b/crates/openhuman-core/src/web3/seams.rsdeleted file mode 100644index 4067b438e6..0000000000--- a/crates/openhuman-core/src/web3/seams.rs+++ /dev/null@@ -1,246 +0,0 @@-//! The host's implementations of the `tinywallet-web3` seams, and the process-//! wide engine and service built on them.-//!-//! `tinywallet-web3` holds the wallet, swap, bridge and dapp logic and none of-//! its configuration; this file is where OpenHuman's own state is plugged in:-//!-//! | Seam | Host implementation |-//! | --- | --- |-//! | `Transport` | [`OpenHumanTransport`](super::wallet::transport::OpenHumanTransport) over the wallet RPC layer |-//! | `RpcEndpoints` | [`HostEndpoints`](super::wallet::endpoints::HostEndpoints), the `OPENHUMAN_WALLET_RPC_*` env |-//! | `WalletSigner` | [`HostSigner`]: keyring, then the loaded wallet module |-//! | `WalletAccounts` | [`HostAccounts`]: the wallet's stored state |-//! | `QuoteScope` | [`TaskLocalScope`]: the chat turn's `APPROVAL_CHAT_CONTEXT` |-//! | `Web3Backend` | [`HostBackend`]: the integrations client |-//!-//! State is instance-owned in the crate; the process holds exactly one engine-//! and one service, built lazily the first time either is needed. Every seam-//! resolves its configuration per call, so building early costs nothing.--use std::sync::{Arc, OnceLock};--use async_trait::async_trait;-use serde_json::Value;-use tinywallet_bus::wire::{- DerivedAccount, Scheme, SecretMaterial, Signature, SignedTransaction, TransactionSpec,-};-use tinywallet_web3::crypto::seams::{WalletAccounts, WalletSigner, Web3Backend};-use tinywallet_web3::crypto::service::Web3Service;-use tinywallet_web3::crypto::wallet::{WalletEngine, WalletSeams, WalletStatus};-use tinywallet_web3::quote::QuoteOwner;-use tinywallet_web3::seams::QuoteScope;--use crate::config::rpc as config_rpc;-use crate::config::Config;-use crate::security::approval::APPROVAL_CHAT_CONTEXT;--use super::client::CryptoClient;-use super::wallet::endpoints::HostEndpoints;-use super::wallet::transport::OpenHumanTransport;-use super::wallet::{self, WalletChain};--const LOG_PREFIX: &str = "[web3:seams]";--/// The engine and the service built over it.-struct Web3Runtime {- engine: Arc<WalletEngine>,- service: Arc<Web3Service>,-}--static RUNTIME: OnceLock<Web3Runtime> = OnceLock::new();--fn runtime() -> &'static Web3Runtime {- RUNTIME.get_or_init(|| {- log::debug!("{LOG_PREFIX} building the wallet engine and web3 service");- let engine = Arc::new(WalletEngine::new(WalletSeams {- transport: Arc::new(OpenHumanTransport::new()),- endpoints: Arc::new(HostEndpoints),- signer: Arc::new(HostSigner),- accounts: Arc::new(HostAccounts),- scope: Arc::new(TaskLocalScope),- }));- let service = Arc::new(Web3Service::new(engine.clone(), Arc::new(HostBackend)));- Web3Runtime { engine, service }- })-}--/// The process-wide wallet engine.-pub fn engine() -> Arc<WalletEngine> {- runtime().engine.clone()-}--/// The process-wide swap/bridge/dapp service.-pub fn service() -> Arc<Web3Service> {- runtime().service.clone()-}--// ----------------------------------------------------------------------------// Signing-// -----------------------------------------------------------------------------/// The chain's name as it appears in signer error messages.-fn label(chain: WalletChain) -> &'static str {- match chain {- WalletChain::Evm => "EVM",- WalletChain::Btc => "BTC",- WalletChain::Solana => "Solana",- WalletChain::Tron => "Tron",- }-}--/// Wording of a failed account derivation.-fn derive_failure(chain: WalletChain, error: &impl std::fmt::Display) -> String {- format!("failed to derive the {} account: {error}", label(chain))-}--/// Wording of a failed transaction signature.-fn sign_transaction_failure(chain: WalletChain, error: &impl std::fmt::Display) -> String {- format!("failed to sign {} transaction: {error}", label(chain))-}--/// Wording of a failed message signature.-fn sign_message_failure(chain: WalletChain, error: &impl std::fmt::Display) -> String {- format!("failed to sign the {} message: {error}", label(chain))-}--/// Derives accounts and signs by handing the recovery phrase to the loaded-/// wallet module over a confidential call.-///-/// The phrase is decrypted here, for the one call, and sent only to a module-/// that has proved it is an artifact this build pinned (see-/// `modules::wallet::attested_proxy`). No private key is assembled in this-/// process, and no mnemonic enters `tinywallet-web3`.-///-/// Errors from before the module call (wallet not set up, keyring, config,-/// decrypt) are returned as they are; errors from the module carry the-/// per-operation prefix the wallet has always used.-#[derive(Debug, Clone, Copy, Default)]-pub struct HostSigner;--impl HostSigner {- /// The config and decrypted secret material for `chain`.- async fn secret(chain: WalletChain) -> Result<(Config, SecretMaterial), String> {- let secret = wallet::secret_material(chain).await?;- let config = config_rpc::load_config_with_timeout().await?;- let mnemonic =- crate::security::encryption::rpc::decrypt_secret(&config, &secret.encrypted_mnemonic)- .await?- .value;- Ok((- config,- SecretMaterial {- mnemonic,- derivation_path: secret.derivation_path,- chain: chain.to_chain(),- },- ))- }-}--#[async_trait]-impl WalletSigner for HostSigner {- async fn derive_account(&self, chain: WalletChain) -> Result<DerivedAccount, String> {- let (config, secret) = Self::secret(chain).await?;- crate::modules::wallet::derive_account(&config, &secret)- .await- .map_err(|e| derive_failure(chain, &e))- }-- async fn sign_transaction(- &self,- chain: WalletChain,- transaction: &TransactionSpec,- ) -> Result<SignedTransaction, String> {- let (config, secret) = Self::secret(chain).await?;- crate::modules::wallet::sign_transaction_in_module(&config, transaction, &secret)- .await- .map_err(|e| sign_transaction_failure(chain, &e))- }-- async fn sign_message(- &self,- chain: WalletChain,- message: &[u8],- scheme: Scheme,- ) -> Result<Signature, String> {- let (config, secret) = Self::secret(chain).await?;- crate::modules::wallet::sign_message(&config, &secret, message, scheme)- .await- .map_err(|e| sign_message_failure(chain, &e))- }-}--// ----------------------------------------------------------------------------// Accounts, scope, backend-// -----------------------------------------------------------------------------/// Reports the wallet's stored set-up state.-#[derive(Debug, Clone, Copy, Default)]-pub struct HostAccounts;--#[async_trait]-impl WalletAccounts for HostAccounts {- async fn status(&self) -> Result<WalletStatus, String> {- Ok(wallet::status().await?.value)- }-}--/// Reads the chat turn's owner from `APPROVAL_CHAT_CONTEXT`.-///-/// `Some(owner)` inside an interactive chat turn (the web channel installs the-/// task-local around `run_chat_task`), `None` for non-chat callers (CLI, direct-/// JSON-RPC, background triage, cron, sub-agents), which have no shared channel-/// a quote id could leak through and so stay executable without an owner.-///-/// `tokio::task_local!` propagates across `.await` but **not** across-/// `tokio::spawn`. If the chat path ever detaches the tool loop onto a-/// freshly-spawned task without re-installing the scope, this silently starts-/// returning `None` and the owner gate becomes a no-op. The crate calls this-/// synchronously on the tool's own task, and the regression test in-/// `seams_tests.rs` pins that it reads the task-local.-#[derive(Debug, Clone, Copy, Default)]-pub struct TaskLocalScope;--impl QuoteScope for TaskLocalScope {- fn current_owner(&self) -> Option<QuoteOwner> {- APPROVAL_CHAT_CONTEXT- .try_with(|ctx| QuoteOwner {- thread_id: ctx.thread_id.clone(),- client_id: ctx.client_id.clone(),- })- .ok()- }-}--/// The hosted swap/bridge quote service, over the integrations client.-///-/// Errors when the user is not signed in (no backend auth token), the same-/// gate the composio tools use.-#[derive(Debug, Clone, Copy, Default)]-pub struct HostBackend;--impl HostBackend {- async fn client() -> Result<CryptoClient, String> {- let config = config_rpc::load_config_with_timeout().await?;- CryptoClient::from_config(&config)- }-}--#[async_trait]-impl Web3Backend for HostBackend {- async fn routes(&self) -> Result<Value, String> {- Self::client().await?.routes().await- }-- async fn swap_tx(&self, body: &Value) -> Result<Value, String> {- Self::client().await?.swap_tx(body).await- }-- async fn bridge_tx(&self, body: &Value) -> Result<Value, String> {- Self::client().await?.bridge_tx(body).await- }-}--#[cfg(test)]-#[path = "seams_tests.rs"]-mod tests;diff --git a/crates/openhuman-core/src/web3/wallet/transport.rs b/crates/openhuman-core/src/web3/wallet/transport.rsdeleted file mode 100644index 077c4dfc4e..0000000000--- a/crates/openhuman-core/src/web3/wallet/transport.rs+++ /dev/null@@ -1,224 +0,0 @@-//! OpenHuman's implementation of the [`tinywallet_bus::rpc::Transport`] seam.-//!-//! `tinywallet-bus` performs no I/O and takes no URLs: it names a-//! [`NetworkId`](tinywallet_bus::rpc::NetworkId) and asks a host to reach it. This-//! module is that host side — the adapter that lets `tinywallet_bus::rpc` and-//! the chain modules run against OpenHuman's existing RPC layer.-//!-//! Everything the crate deliberately refused to own lives on this side of the-//! seam and is reused from [`super::rpc`] unchanged:-//!-//! - **endpoint resolution**, including the `OPENHUMAN_WALLET_RPC_<CHAIN>`-//! overrides the e2e tests point at a mock;-//! - **URL redaction**, so an endpoint carrying an API key never reaches a log;-//! - the shared `reqwest` client and its connection pool.-//!-//! ## Error mapping is the part worth reviewing-//!-//! `tinywallet-bus` splits transport failures into retryable-//! ([`TransportError::Unreachable`]) and authoritative-//! ([`TransportError::Rpc`]), and a host's failover depends on that-//! distinction: retrying an authoritative "insufficient funds" gets the same-//! answer, while retrying an ambiguous failure risks a double broadcast.-//!-//! OpenHuman's RPC helpers flatten both into `String`, so this adapter cannot-//! recover the distinction perfectly. It classifies conservatively — **anything-//! it cannot prove is a transport failure is reported as authoritative** — so-//! an unclassifiable error stops a failover loop rather than driving it. That-//! is the safe direction: a missed retry costs a request, a wrong retry can-//! cost a duplicate transaction.--use async_trait::async_trait;-use log::debug;-use serde_json::Value;-use tinywallet_crypto::rpc::{NetworkId, Transport, TransportError, TransportResult};--use tinywallet_web3::crypto::defaults::EvmNetwork;--use super::endpoints::{rpc_url_for_chain, rpc_url_for_evm_network};-use super::ops::WalletChain;-use super::rpc::{redact_rpc_url, rest_get_text, rest_post_text, rpc_call_to};--/// Adapter over OpenHuman's wallet RPC layer.-///-/// Stateless — endpoint resolution happens per call so an env override applied-/// mid-process (as the e2e harness does) is picked up without rebuilding it.-#[derive(Debug, Clone, Copy, Default)]-pub struct OpenHumanTransport;--impl OpenHumanTransport {- /// Build the adapter.- #[must_use]- pub const fn new() -> Self {- Self- }-}--/// Map a `tinywallet-bus` network onto OpenHuman's chain enum plus a base URL.-#[allow(unreachable_patterns)]-fn resolve(network: NetworkId) -> Result<String, TransportError> {- match network.chain {- tinywallet_bus::Chain::Evm => {- // An EVM request names its EIP-155 chain id; resolving it here is- // what keeps `tinywallet-bus` free of OpenHuman's network enum.- let chain_id = network.evm_chain_id.ok_or_else(|| TransportError::Rpc {- network,- message: "EVM requests require an EIP-155 chain id".to_string(),- })?;- let evm = EvmNetwork::ALL- .iter()- .copied()- .find(|n| n.chain_id() == chain_id)- .ok_or_else(|| TransportError::Rpc {- network,- message: format!("no configured EVM endpoint for chain id {chain_id}"),- })?;- Ok(rpc_url_for_evm_network(evm))- }- tinywallet_bus::Chain::Btc => Ok(rpc_url_for_chain(WalletChain::Btc)),- tinywallet_bus::Chain::Solana => Ok(rpc_url_for_chain(WalletChain::Solana)),- tinywallet_bus::Chain::Tron => Ok(rpc_url_for_chain(WalletChain::Tron)),- // `tinywallet_bus::Chain` is `#[non_exhaustive]`, so a future variant must- // be handled. Reporting it as authoritative is correct: no endpoint is- // configured for it, and retrying elsewhere cannot change that.- other => Err(TransportError::Rpc {- network,- message: format!("no endpoint configured for chain {other}"),- }),- }-}--/// Join a base URL and a relative path without doubling the separator.-fn join(base: &str, path: &str) -> String {- format!(- "{}/{}",- base.trim_end_matches('/'),- path.trim_start_matches('/')- )-}--/// Classify a flattened error string.-///-/// See the module docs: only messages this layer itself produced for a-/// transport failure are treated as retryable. Everything else is-/// authoritative, so an unclassifiable error stops a failover rather than-/// driving one.-pub(crate) fn classify(network: NetworkId, message: String) -> TransportError {- const TRANSPORT_MARKERS: [&str; 2] = ["transport failed", "read body failed"];- if TRANSPORT_MARKERS.iter().any(|m| message.contains(m)) {- TransportError::Unreachable { network, message }- } else {- TransportError::Rpc { network, message }- }-}--#[async_trait]-impl Transport for OpenHumanTransport {- async fn json_rpc(- &self,- network: NetworkId,- method: &str,- params: Value,- ) -> TransportResult<Value> {- let url = resolve(network)?;- debug!(- "[wallet:transport] json_rpc chain={} method={method} endpoint={}",- network.chain,- redact_rpc_url(&url)- );- match rpc_call_to::<Value>(&url, method, params).await {- Ok(value) => {- debug!(- "[wallet:transport] json_rpc chain={} method={method} outcome=success",- network.chain- );- Ok(value)- }- Err(message) => {- let error = classify(network, message);- debug!(- "[wallet:transport] json_rpc chain={} method={method} outcome={}",- network.chain,- if error.is_retryable() {- "unreachable"- } else {- "rpc"- }- );- Err(error)- }- }- }-- async fn rest_get(&self, network: NetworkId, path: &str) -> TransportResult<String> {- let url = join(&resolve(network)?, path);- debug!(- "[wallet:transport] rest_get chain={} path={path} endpoint={}",- network.chain,- redact_rpc_url(&url)- );- match rest_get_text(&url).await {- Ok(value) => {- debug!(- "[wallet:transport] rest_get chain={} path={path} outcome=success",- network.chain- );- Ok(value)- }- Err(message) => {- let error = classify(network, message);- debug!(- "[wallet:transport] rest_get chain={} path={path} outcome={}",- network.chain,- if error.is_retryable() {- "unreachable"- } else {- "rpc"- }- );- Err(error)- }- }- }-- async fn rest_post(- &self,- network: NetworkId,- path: &str,- body: String,- content_type: &str,- ) -> TransportResult<String> {- let url = join(&resolve(network)?, path);- debug!(- "[wallet:transport] rest_post chain={} path={path} endpoint={}",- network.chain,- redact_rpc_url(&url)- );- match rest_post_text(&url, &body, content_type).await {- Ok(value) => {- debug!(- "[wallet:transport] rest_post chain={} path={path} outcome=success",- network.chain- );- Ok(value)- }- Err(message) => {- let error = classify(network, message);- debug!(- "[wallet:transport] rest_post chain={} path={path} outcome={}",- network.chain,- if error.is_retryable() {- "unreachable"- } else {- "rpc"- }- );- Err(error)- }- }- }-}--#[cfg(test)]-#[path = "transport_tests.rs"]-mod tests;diff --git a/crates/openhuman-core/src/web3/x402/budget.rs b/crates/openhuman-core/src/web3/x402/budget.rsdeleted file mode 100644index a7555c38a3..0000000000--- a/crates/openhuman-core/src/web3/x402/budget.rs+++ /dev/null@@ -1,52 +0,0 @@-//! Where the x402 spending limits come from.-//!-//! The crate owns the budget type and its defaults (1 / 10 / 100 USDC per-//! request / day / month); which limits a process runs with is host policy, so-//! the `OPENHUMAN_X402_*` environment overrides are read here.--use log::debug;-use tinywallet_x402::ledger::SpendingBudget;--const LOG_PREFIX: &str = "[x402::budget]";--/// Override for [`SpendingBudget::per_request_max_atomic`].-const ENV_PER_REQUEST_MAX: &str = "OPENHUMAN_X402_PER_REQUEST_MAX";-/// Override for [`SpendingBudget::daily_max_atomic`].-const ENV_DAILY_MAX: &str = "OPENHUMAN_X402_DAILY_MAX";-/// Override for [`SpendingBudget::monthly_max_atomic`].-const ENV_MONTHLY_MAX: &str = "OPENHUMAN_X402_MONTHLY_MAX";--/// The crate's default budget with the process environment's overrides applied.-pub(crate) fn budget_from_env() -> SpendingBudget {- budget_from(|name| std::env::var(name).ok())-}--/// [`budget_from_env`] over an arbitrary variable lookup, so the override rules-/// are testable without touching the process environment.-///-/// A value that is not a base-10 `u64` is ignored and the default stays.-pub(crate) fn budget_from(get: impl Fn(&str) -> Option<String>) -> SpendingBudget {- let mut budget = SpendingBudget::default();- let apply = |name: &str, label: &str, slot: &mut u64| {- if let Some(n) = get(name).and_then(|v| v.parse::<u64>().ok()) {- debug!("{LOG_PREFIX} env override {label}={n}");- *slot = n;- }- };- apply(- ENV_PER_REQUEST_MAX,- "per_request_max",- &mut budget.per_request_max_atomic,- );- apply(ENV_DAILY_MAX, "daily_max", &mut budget.daily_max_atomic);- apply(- ENV_MONTHLY_MAX,- "monthly_max",- &mut budget.monthly_max_atomic,- );- budget-}--#[cfg(test)]-#[path = "budget_tests.rs"]-mod tests;diff --git a/crates/openhuman-core/src/web3/x402/records.rs b/crates/openhuman-core/src/web3/x402/records.rsdeleted file mode 100644index e7fdca4cb7..0000000000--- a/crates/openhuman-core/src/web3/x402/records.rs+++ /dev/null@@ -1,45 +0,0 @@-//! The ledger record a payment starts with, for callers outside the-//! `x402_request` tool (the `http_request` 402 fallback).-//!-//! The tool builds its own records inside the crate; this is the same rule for-//! the host's other writer, so both attribute a payment identically:-//! `session_id` is always the ledger's own session (so the session total counts-//! the payment) and `thread_id` is the chat thread from `APPROVAL_CHAT_CONTEXT`.--use tinywallet_x402::ledger::{self, PaymentRecord, PaymentStatus};-use tinywallet_x402::protocol::X402PaymentResult;-use tinywallet_x402::thread::ThreadScope;--use super::seams::TaskLocalThread;--/// A `Pending` record for `payment`, stamped with the ledger's session and the-/// active chat thread (if any). Later states are written as new lines with the-/// same `id`.-#[allow(clippy::cast_precision_loss)] // atomic USDC amounts stay far below 2^53-pub fn pending_record(payment: &X402PaymentResult) -> PaymentRecord {- // A ledger that is not initialised has no session to name; the payment- // would have failed at the budget check before reaching here.- let session_id = ledger::with_ledger(|l| l.session_id().to_string()).unwrap_or_default();- PaymentRecord {- id: uuid::Uuid::new_v4().to_string(),- url: payment.url.clone(),- asset: payment.asset.clone(),- amount_atomic: payment.amount_atomic,- amount_display: format!("{:.6} USDC", payment.amount_atomic as f64 / 1_000_000.0),- recipient: payment.recipient.clone(),- network: payment.network.clone(),- tx_signature: None,- status: PaymentStatus::Pending,- 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,- thread_id: TaskLocalThread.current_thread(),- }-}--#[cfg(test)]-#[path = "records_tests.rs"]-mod tests;diff --git a/crates/openhuman-core/src/web3/x402/records_tests.rs b/crates/openhuman-core/src/web3/x402/records_tests.rsdeleted file mode 100644index 83cbdd4db1..0000000000--- a/crates/openhuman-core/src/web3/x402/records_tests.rs+++ /dev/null@@ -1,83 +0,0 @@-use super::*;-use crate::security::approval::{ApprovalChatContext, APPROVAL_CHAT_CONTEXT};-use crate::web3::wallet::test_support::TEST_LOCK;-use tinywallet_x402::ledger::{self, PaymentStatus};--const SESSION: &str = "x402-boot-session";--fn chat_ctx(thread: &str) -> ApprovalChatContext {- ApprovalChatContext {- thread_id: thread.to_string(),- client_id: "client".to_string(),- request_id: None,- }-}--/// A payment as `handle_402_and_pay` hands it back: 2500 atomic USDC held on-/// the process-wide ledger.-fn payment() -> X402PaymentResult {- X402PaymentResult {- header_value: "header".into(),- amount_atomic: 2_500,- asset: "usdc-mint".into(),- recipient: "recipient".into(),- network: "solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp".into(),- url: "https://x402.example.test/thing".into(),- authorization_valid_until: None,- solana_last_valid_block_height: None,- reservation: ledger::reserve(2_500).unwrap().unwrap(),- }-}--fn init(temp: &tempfile::TempDir) {- super::super::init_ledger(temp.path(), SESSION);-}--/// The fallback path's pending record carries the ledger's session, so the-/// payment counts toward `session_total` once it settles, and the chat thread.-#[tokio::test]-async fn a_fallback_payment_counts_in_the_session_total_and_names_its_thread() {- let _lock = TEST_LOCK.lock().await;- let temp = tempfile::tempdir().unwrap();- init(&temp);- let payment = payment();-- let record = APPROVAL_CHAT_CONTEXT- .scope(chat_ctx("thread-a"), async { pending_record(&payment) })- .await;-- assert_eq!(record.status, PaymentStatus::Pending);- assert_eq!(record.session_id, SESSION);- assert_eq!(record.thread_id.as_deref(), Some("thread-a"));- assert_eq!(record.amount_atomic, 2_500);- assert_eq!(record.amount_display, "0.002500 USDC");- assert_eq!(record.url, payment.url);-- let mut settled = record.clone();- settled.status = PaymentStatus::Settled;- payment.reservation.commit(settled);- let summary = ledger::with_ledger(|l| l.summary()).unwrap();- assert_eq!(summary.session_total_atomic, 2_500);- assert_eq!(summary.session_count, 1);-}--#[tokio::test]-async fn a_payment_outside_a_chat_turn_has_no_thread_but_the_same_session() {- let _lock = TEST_LOCK.lock().await;- let temp = tempfile::tempdir().unwrap();- init(&temp);-- let record = pending_record(&payment());-- assert_eq!(record.thread_id, None);- assert_eq!(record.session_id, SESSION);-}--#[tokio::test]-async fn every_payment_gets_its_own_record_id() {- let _lock = TEST_LOCK.lock().await;- let temp = tempfile::tempdir().unwrap();- init(&temp);-- assert_ne!(pending_record(&payment()).id, pending_record(&payment()).id);-}diff --git a/crates/openhuman-core/src/web3/x402/seams.rs b/crates/openhuman-core/src/web3/x402/seams.rsdeleted file mode 100644index 0f57e0192e..0000000000--- a/crates/openhuman-core/src/web3/x402/seams.rs+++ /dev/null@@ -1,326 +0,0 @@-//! The host side of the `tinywallet-x402` seams.-//!-//! The crate never sees a mnemonic, a config or a proxy setting. It is handed:-//!-//! - a [`PaymentSigner`]: [`WalletPaymentSigner`] resolves the wallet's-//! encrypted secret from the keyring state, decrypts it with the configured-//! key, and asks the loaded `tinywallet` module to derive the account and sign.-//! The decrypted phrase lives only for the length of one confidential call;-//! what crosses back to the crate is an address and finished signatures.-//! - a `Transport`: [`OpenHumanTransport`](crate::web3::wallet::transport::OpenHumanTransport),-//! the failover-aware RPC adapter the wallet already uses, for the Solana-//! blockhash.-//! - a [`ProxyPolicy`]: [`RuntimeProxyPolicy`] refuses direct, address-pinned-//! requests when runtime or environment proxy policy requires a proxy.-//! - a [`ThreadScope`]: [`TaskLocalThread`] names the chat thread running the-//! tool call, so the ledger can attribute the payment to it.-//!-//! Every `Err(String)` these return is the text a user sees, prefixed exactly as-//! the payment flow did before it moved into the crate (`wallet secret: …`,-//! `load config: …`, `decrypt mnemonic: …`, `derive account: …`).--use std::sync::Arc;--use async_trait::async_trait;-use log::debug;-use tinytools_std::network::NetGate;-use tinytools_std::url_guard::{normalize_allowed_domains, validate_url_with_dns_check};-use tinywallet_x402::crypto::{CryptoPayments, PaymentAccount, PaymentSigner, SignScheme};-use tinywallet_x402::protocol::ProxyPolicy;-use tinywallet_x402::thread::ThreadScope;-use tinywallet_x402::tools::{- AuthorizedRequest, ProposedRequest, RequestAuthorizationError, RequestGuard, X402RequestTool,-};-use tinywallet_x402::wire::PaymentChain;--use crate::security::approval::APPROVAL_CHAT_CONTEXT;-use crate::security::SecurityPolicy;-use crate::web3::wallet::transport::OpenHumanTransport;-use crate::web3::wallet::WalletChain;--const LOG_PREFIX: &str = "[x402::seams]";--/// The wallet as x402 signs with it: keyring secret, decrypt, wallet module.-#[derive(Debug, Clone, Copy, Default)]-pub(crate) struct WalletPaymentSigner;--/// The runtime and environment proxy configuration for x402 outbound HTTP.-#[derive(Debug, Clone, Copy, Default)]-pub(crate) struct RuntimeProxyPolicy;--#[derive(Debug)]-pub(crate) struct HostRequestGuard {- security: Arc<SecurityPolicy>,- allowed_domains: Vec<String>,-}--#[async_trait]-impl RequestGuard for HostRequestGuard {- fn needs_approval(&self) -> bool {- self.security.network_needs_approval()- }-- async fn authorize(- &self,- request: &ProposedRequest,- ) -> Result<AuthorizedRequest, RequestAuthorizationError> {- if !self.security.can_act() {- return Err(RequestAuthorizationError::Denied(- "Action blocked: autonomy is read-only".into(),- ));- }- let parsed = reqwest::Url::parse(&request.url)- .map_err(|error| RequestAuthorizationError::InvalidDestination(error.to_string()))?;- if parsed.scheme() != "https" {- return Err(RequestAuthorizationError::InvalidDestination(- "x402 payment requests require HTTPS".into(),- ));- }- let host = parsed- .host_str()- .map(str::to_string)- .unwrap_or_else(|| "unknown".to_string());- if let Some(reason) = self.security.local_only_block(&host) {- return Err(RequestAuthorizationError::Denied(- reason- .strip_prefix("[policy-blocked] ")- .unwrap_or(&reason)- .to_string(),- ));- }- if self.security.is_rate_limited() {- return Err(RequestAuthorizationError::Denied(- "Action blocked: rate limit exceeded".into(),- ));- }- let target = validate_url_with_dns_check(&request.url, &self.allowed_domains)- .await- .map_err(|error| RequestAuthorizationError::InvalidDestination(error.to_string()))?;- if !self.security.record_action() {- return Err(RequestAuthorizationError::Denied(- "Action blocked: rate limit exceeded".into(),- ));- }- // A 402 retry adds PAYMENT-SIGNATURE even when the original request- // has no headers. Disclose that potential metadata before either send.- self.security- .disclose(&target.host, request.body.is_some(), true);- let mut approved_request = request.clone();- approved_request.url = target.url;- Ok(AuthorizedRequest {- request: approved_request,- host: target.host,- addrs: target.addrs,- })- }-}--/// The chat thread running the current tool call, read from-/// `APPROVAL_CHAT_CONTEXT`.-///-/// `Some(thread_id)` inside an interactive chat turn (the web channel installs the-/// task-local around the run), `None` for CLI, direct JSON-RPC, cron and other-/// non-chat callers, whose payments then carry no `thread_id`. The ledger's-/// `session_id` never comes from here: it is always the ledger's own.-///-/// `tokio::task_local!` propagates across `.await` but **not** across-/// `tokio::spawn`; the crate calls this synchronously on the tool's own task, and-/// the regression test in `seams_tests.rs` pins that it reads the task-local.-#[derive(Debug, Clone, Copy, Default)]-pub(crate) struct TaskLocalThread;--impl ThreadScope for TaskLocalThread {- fn current_thread(&self) -> Option<String> {- APPROVAL_CHAT_CONTEXT- .try_with(|ctx| ctx.thread_id.clone())- .ok()- }-}--/// The wallet chain a payment chain is signed as.-fn wallet_chain(chain: PaymentChain) -> WalletChain {- match chain {- PaymentChain::Solana => WalletChain::Solana,- PaymentChain::Evm => WalletChain::Evm,- }-}--/// The bus chain the wallet module derives for.-fn bus_chain(chain: PaymentChain) -> tinywallet_bus::Chain {- match chain {- PaymentChain::Solana => tinywallet_bus::Chain::Solana,- PaymentChain::Evm => tinywallet_bus::Chain::Evm,- }-}--/// Resolve the phrase to sign with: the config, and the wallet's decrypted-/// mnemonic packaged for a confidential call.-///-/// Derivation and signing both happen inside the loaded wallet module, so this-/// process never holds a private key. The phrase is handed over on a-/// confidential call, and only to a module that has proved it is an artifact this-/// build pinned.-async fn signing_secret(- chain: PaymentChain,-) -> Result<(crate::config::Config, tinywallet_bus::wire::SecretMaterial), String> {- let secret = crate::web3::wallet::secret_material(wallet_chain(chain))- .await- .map_err(|e| format!("wallet secret: {e}"))?;-- let config = crate::config::rpc::load_config_with_timeout()- .await- .map_err(|e| format!("load config: {e}"))?;-- let mnemonic =- crate::security::encryption::rpc::decrypt_secret(&config, &secret.encrypted_mnemonic)- .await- .map_err(|e| format!("decrypt mnemonic: {e}"))?- .value;-- Ok((- config,- tinywallet_bus::wire::SecretMaterial {- mnemonic,- derivation_path: secret.derivation_path.clone(),- chain: bus_chain(chain),- },- ))-}--#[async_trait]-impl PaymentSigner for WalletPaymentSigner {- async fn account(&self, chain: PaymentChain) -> Result<PaymentAccount, String> {- debug!("{LOG_PREFIX} account chain={chain:?}");- let (config, secret) = signing_secret(chain).await?;- let account = crate::modules::wallet::derive_account(&config, &secret)- .await- .map_err(|e| match chain {- PaymentChain::Solana => format!("derive account: {e}"),- PaymentChain::Evm => format!("derive EVM signer: {e}"),- })?;- // The module answers with the address only; the crate decodes a Solana- // public key from it.- Ok(PaymentAccount {- address: account.address,- pubkey: None,- })- }-- async fn sign(- &self,- chain: PaymentChain,- message: &[u8],- scheme: SignScheme,- ) -> Result<Vec<u8>, String> {- debug!(- "{LOG_PREFIX} sign chain={chain:?} scheme={scheme:?} bytes={}",- message.len()- );- let (config, secret) = signing_secret(chain).await?;- let wire_scheme = match scheme {- SignScheme::Ed25519 => tinywallet_bus::wire::Scheme::Ed25519,- SignScheme::Secp256k1Digest => tinywallet_bus::wire::Scheme::Secp256k1Prehash,- };- // Signed in the module; the private key is never assembled here.- let signature =- crate::modules::wallet::sign_message(&config, &secret, message, wire_scheme)- .await- .map_err(|e| e.to_string())?;- signature_bytes(signature)- }-}--/// The raw bytes the crate expects from the module's signature: 64 for ed25519,-/// `r ‖ s ‖ recovery_id` (65) for secp256k1.-fn signature_bytes(signature: tinywallet_bus::wire::Signature) -> Result<Vec<u8>, String> {- match signature {- tinywallet_bus::wire::Signature::Ed25519 { signature_hex } => {- hex::decode(&signature_hex).map_err(|e| format!("invalid signature hex: {e}"))- }- tinywallet_bus::wire::Signature::Secp256k1 {- rs_hex,- recovery_id,- } => {- let mut bytes =- hex::decode(&rs_hex).map_err(|e| format!("invalid signature hex: {e}"))?;- if bytes.len() != 64 {- return Err("the wallet module returned a malformed signature".to_string());- }- bytes.push(recovery_id);- Ok(bytes)- }- // `Signature` is non-exhaustive; a scheme this build has never heard of- // cannot be paid with.- _ => Err("the wallet module returned an unsupported signature".to_string()),- }-}--impl ProxyPolicy for RuntimeProxyPolicy {- fn apply(&self, builder: reqwest13::ClientBuilder, service: &str) -> reqwest13::ClientBuilder {- super::proxy_compat::apply(builder, service, &crate::config::runtime_proxy_config())- }-- fn allows_direct_connection(&self, service: &str) -> bool {- let config = crate::config::runtime_proxy_config();- direct_connection_allowed(&config, service, |key| {- std::env::var_os(key).is_some_and(|value| !value.is_empty())- })- }-}--/// A guarded request must connect to its vetted address directly. Treat any-/// configured proxy for this service, including process proxy variables, as-/// requiring the proxy until the host can pin an address through that proxy.-fn direct_connection_allowed(- config: &crate::config::ProxyConfig,- service: &str,- env_has_value: impl Fn(&str) -> bool,-) -> bool {- const PROXY_ENV_KEYS: &[&str] = &[- "HTTP_PROXY",- "HTTPS_PROXY",- "ALL_PROXY",- "http_proxy",- "https_proxy",- "all_proxy",- ];- !((config.enabled && config.scope == crate::config::ProxyScope::Environment)- || config.should_apply_to_service(service)- || PROXY_ENV_KEYS.iter().any(|key| env_has_value(key)))-}--/// The crypto rail's payment builder, over OpenHuman's wallet and transport.-pub(crate) fn payments() -> CryptoPayments {- CryptoPayments::new(- Arc::new(WalletPaymentSigner),- Arc::new(OpenHumanTransport::new()),- )-}--/// The `x402_request` tool, over the same seams.-pub(crate) fn request_tool(- security: Arc<SecurityPolicy>,- allowed_domains: Vec<String>,-) -> X402RequestTool {- X402RequestTool::new(- Arc::new(WalletPaymentSigner),- Arc::new(OpenHumanTransport::new()),- Arc::new(RuntimeProxyPolicy),- )- .with_thread_scope(Arc::new(TaskLocalThread))- .with_request_guard(Arc::new(host_request_guard(security, allowed_domains)))-}--fn host_request_guard(- security: Arc<SecurityPolicy>,- allowed_domains: Vec<String>,-) -> HostRequestGuard {- HostRequestGuard {- security,- allowed_domains: normalize_allowed_domains(allowed_domains),- }-}--#[cfg(test)]-#[path = "seams_tests.rs"]-mod tests;diff --git a/crates/openhuman-core/src/web3/x402/seams_tests.rs b/crates/openhuman-core/src/web3/x402/seams_tests.rsdeleted file mode 100644index f6eeb96c32..0000000000--- a/crates/openhuman-core/src/web3/x402/seams_tests.rs+++ /dev/null@@ -1,460 +0,0 @@-use super::*;--use base64::Engine as _;-use reqwest::header::{HeaderMap, HeaderValue};-use tinywallet_bus::wire::Signature;-use tinywallet_x402::protocol::{PaymentBuilder, X402Error};-use tinywallet_x402::wire::{- PaymentExtra, PaymentRequired, PaymentRequirements, ResourceInfo, SOLANA_MAINNET_CAIP2,- USDC_MINT_MAINNET, X402_VERSION,-};--// ----------------------------------------------------------------------------// Signature decoding: what the wallet module returns, as bytes the crate takes-// -----------------------------------------------------------------------------#[test]-fn an_ed25519_signature_becomes_its_64_bytes() {- let bytes = signature_bytes(Signature::Ed25519 {- signature_hex: "ab".repeat(64),- })- .unwrap();- assert_eq!(bytes, vec![0xab; 64]);-}--#[test]-fn a_secp256k1_signature_is_r_s_then_the_recovery_id() {- let bytes = signature_bytes(Signature::Secp256k1 {- rs_hex: "cd".repeat(64),- recovery_id: 1,- })- .unwrap();- assert_eq!(bytes.len(), 65);- assert_eq!(&bytes[..64], &[0xcd; 64][..]);- assert_eq!(bytes[64], 1);-}--#[test]-fn a_signature_that_is_not_hex_is_rejected() {- let err = signature_bytes(Signature::Ed25519 {- signature_hex: "zz".into(),- })- .unwrap_err();- assert!(err.starts_with("invalid signature hex: "), "{err}");- let err = signature_bytes(Signature::Secp256k1 {- rs_hex: "zz".into(),- recovery_id: 0,- })- .unwrap_err();- assert!(err.starts_with("invalid signature hex: "), "{err}");-}--#[test]-fn a_secp256k1_signature_of_the_wrong_length_is_malformed() {- let err = signature_bytes(Signature::Secp256k1 {- rs_hex: "cd".repeat(63),- recovery_id: 0,- })- .unwrap_err();- assert_eq!(err, "the wallet module returned a malformed signature");-}--#[test]-fn payment_chains_map_onto_the_wallets_chains() {- assert!(matches!(- wallet_chain(PaymentChain::Solana),- WalletChain::Solana- ));- assert!(matches!(wallet_chain(PaymentChain::Evm), WalletChain::Evm));- assert_eq!(- bus_chain(PaymentChain::Solana),- tinywallet_bus::Chain::Solana- );- assert_eq!(bus_chain(PaymentChain::Evm), tinywallet_bus::Chain::Evm);-}--// ----------------------------------------------------------------------------// The seams compose into the crate's payment flow-// -----------------------------------------------------------------------------#[test]-fn the_proxy_policy_yields_a_buildable_client() {- let builder = RuntimeProxyPolicy.apply(reqwest13::Client::builder(), "tool.x402_request");- assert!(builder.build().is_ok());-}--#[test]-fn x402_direct_egress_requires_absent_runtime_and_environment_proxies() {- let service = "tool.x402_request";- let clear = |_: &str| false;- let mut config = crate::config::ProxyConfig::default();- assert!(direct_connection_allowed(&config, service, clear));-- config.enabled = true;- config.http_proxy = Some("http://proxy.example:3128".into());- assert!(!direct_connection_allowed(&config, service, clear));-- config.scope = crate::config::ProxyScope::Services;- config.services = vec!["tool.http_request".into()];- assert!(direct_connection_allowed(&config, service, clear));- assert!(direct_connection_allowed(&config, service, |candidate| {- candidate == "OPENHUMAN_HTTP_PROXY"- }));- config.services = vec!["tool.*".into()];- assert!(!direct_connection_allowed(&config, service, clear));-- config.scope = crate::config::ProxyScope::Environment;- assert!(!direct_connection_allowed(&config, service, clear));-- config.enabled = false;- for key in [- "HTTP_PROXY",- "HTTPS_PROXY",- "ALL_PROXY",- "http_proxy",- "https_proxy",- "all_proxy",- ] {- assert!(- !direct_connection_allowed(&config, service, |candidate| candidate == key),- "{key} must refuse direct egress"- );- }- for key in [- "OPENHUMAN_HTTP_PROXY",- "OPENHUMAN_HTTPS_PROXY",- "OPENHUMAN_ALL_PROXY",- ] {- assert!(- direct_connection_allowed(&config, service, |candidate| candidate == key),- "{key} follows the disabled runtime proxy config"- );- }-}--fn proposed_request(url: &str) -> ProposedRequest {- ProposedRequest {- url: url.into(),- method: reqwest::Method::POST,- headers: vec![("x-custom".into(), "retained".into())],- body: Some("private body".into()),- }-}--#[tokio::test]-async fn x402_guard_authorizes_the_complete_request_and_pins_destination() {- let _env_lock = crate::config::TEST_ENV_LOCK.lock().await;- let guard = HostRequestGuard {- security: Arc::new(SecurityPolicy::default()),- allowed_domains: vec![],- };- let proposed = proposed_request("https://8.8.8.8/path");- let authorized = guard.authorize(&proposed).await.unwrap();- assert_eq!(authorized.request.url, proposed.url);- assert_eq!(authorized.request.method, proposed.method);- assert_eq!(authorized.request.headers, proposed.headers);- assert_eq!(authorized.request.body, proposed.body);- assert_eq!(authorized.host, "8.8.8.8");- assert_eq!(authorized.addrs.len(), 1);- assert_eq!(authorized.addrs[0].ip().to_string(), "8.8.8.8");- assert_eq!(authorized.addrs[0].port(), 443);-}--#[tokio::test]-async fn x402_guard_discloses_possible_payment_proof_metadata() {- use crate::core::events::DomainEvent;- use crate::security::egress::DataKind;-- let _env_lock = crate::config::TEST_ENV_LOCK.lock().await;- crate::core::bus::init().await.expect("bus init");- let mut events = crate::core::bus::BUS.get().unwrap().receiver();- let guard = HostRequestGuard {- security: Arc::new(SecurityPolicy::default()),- allowed_domains: vec![],- };-- guard- .authorize(&proposed_request("https://1.1.1.1/"))- .await- .expect("public destination should be authorized");- loop {- match events.recv().await {- Some(DomainEvent::ExternalTransferPending { descriptor, .. })- if descriptor.service == "1.1.1.1" =>- {- assert!(descriptor.data_kinds.contains(&DataKind::Metadata));- break;- }- Some(_) => continue,- None => panic!("bus closed before x402 disclosure"),- }- }-}--#[tokio::test]-async fn x402_guard_rejects_readonly_and_private_destinations() {- let _env_lock = crate::config::TEST_ENV_LOCK.lock().await;- let readonly = HostRequestGuard {- security: Arc::new(SecurityPolicy {- autonomy: crate::security::AutonomyLevel::ReadOnly,- ..SecurityPolicy::default()- }),- allowed_domains: vec![],- };- assert!(matches!(- readonly- .authorize(&proposed_request("https://8.8.8.8/"))- .await,- Err(RequestAuthorizationError::Denied(_))- ));-- let guard = HostRequestGuard {- security: Arc::new(SecurityPolicy::default()),- allowed_domains: vec![],- };- assert!(matches!(- guard- .authorize(&proposed_request("https://127.0.0.1/"))- .await,- Err(RequestAuthorizationError::InvalidDestination(_))- ));-}--#[tokio::test]-async fn x402_guard_rejects_cleartext_payment_destinations() {- let _env_lock = crate::config::TEST_ENV_LOCK.lock().await;- let guard = HostRequestGuard {- security: Arc::new(SecurityPolicy::default()),- allowed_domains: vec![],- };- assert!(matches!(- guard.authorize(&proposed_request("http://8.8.8.8/")).await,- Err(RequestAuthorizationError::InvalidDestination(reason)) if reason.contains("HTTPS")- ));-}--#[tokio::test]-async fn x402_rejected_destinations_do_not_exhaust_the_action_budget() {- let _env_lock = crate::config::TEST_ENV_LOCK.lock().await;- let guard = HostRequestGuard {- security: Arc::new(SecurityPolicy {- max_actions_per_hour: 1,- ..SecurityPolicy::default()- }),- allowed_domains: vec![],- };- assert!(matches!(- guard- .authorize(&proposed_request("https://127.0.0.1/"))- .await,- Err(RequestAuthorizationError::InvalidDestination(_))- ));- assert!(guard- .authorize(&proposed_request("https://8.8.8.8/"))- .await- .is_ok());- assert!(matches!(- guard.authorize(&proposed_request("https://8.8.8.8/"))- .await,- Err(RequestAuthorizationError::Denied(reason)) if reason.contains("rate limit")- ));- assert!(matches!(- guard.authorize(&proposed_request("https://127.0.0.1/"))- .await,- Err(RequestAuthorizationError::Denied(reason)) if reason.contains("rate limit")- ));-}--#[tokio::test]-async fn x402_tool_runs_the_host_guard_before_network_or_payment() {- use tinytools::Tool;-- let _env_lock = crate::config::TEST_ENV_LOCK.lock().await;-- let security = Arc::new(SecurityPolicy::default());- let blocked_private = request_tool(security.clone(), vec![])- .execute(serde_json::json!({"url": "https://127.0.0.1:1/"}))- .await- .unwrap();- assert!(blocked_private.is_error);- assert!(blocked_private.text().contains("[policy-blocked]"));-- let blocked_domain = request_tool(security, vec!["example.com".into()])- .execute(serde_json::json!({"url": "https://8.8.8.8/"}))- .await- .unwrap();- assert!(blocked_domain.is_error);- assert!(blocked_domain.text().contains("[policy-blocked]"));-- let blocked_cleartext = request_tool(Arc::new(SecurityPolicy::default()), vec![])- .execute(serde_json::json!({"url": "http://8.8.8.8:1/"}))- .await- .unwrap();- assert!(blocked_cleartext.is_error);- assert!(blocked_cleartext.text().contains("require HTTPS"));-}--#[tokio::test]-async fn x402_host_guard_normalizes_the_network_allowlist() {- let _env_lock = crate::config::TEST_ENV_LOCK.lock().await;- let security = Arc::new(SecurityPolicy::default());- let allowed = host_request_guard(security.clone(), vec!["HTTPS://8.8.8.8/path".into()]);- assert!(allowed- .authorize(&proposed_request("https://8.8.8.8/"))- .await- .is_ok());-- let malformed = host_request_guard(security, vec![" ".into()]);- assert!(matches!(- malformed- .authorize(&proposed_request("https://8.8.8.8/"))- .await,- Err(RequestAuthorizationError::InvalidDestination(_))- ));-}--#[test]-fn the_tool_is_built_from_the_host_seams() {- use tinytools::Tool;- let security = Arc::new(SecurityPolicy::default());- assert_eq!(- request_tool(security.clone(), vec![]).name(),- "x402_request"- );- assert_eq!(- super::super::request_tool(security, vec![]).name(),- "x402_request"- );-}--fn solana_challenge_headers() -> HeaderMap {- let challenge = PaymentRequired {- x402_version: X402_VERSION,- error: None,- resource: ResourceInfo {- url: "https://x402.example.test/thing".into(),- description: None,- mime_type: None,- },- accepts: vec![PaymentRequirements {- scheme: "exact".into(),- network: SOLANA_MAINNET_CAIP2.into(),- amount: "10000".into(),- asset: USDC_MINT_MAINNET.into(),- pay_to: "2wKupLR9q6wXYppw8Gr2NvWxKBUqm4PPJKkQfoxHDBg4".into(),- max_timeout_seconds: 60,- extra: Some(PaymentExtra {- fee_payer: Some("EwWqGE4ZFKLofuestmU4LDdK7XM1N4ALgdZccwYugwGd".into()),- memo: None,- name: None,- version: None,- }),- }],- extensions: serde_json::Map::new(),- };- let mut headers = HeaderMap::new();- headers.insert(- "PAYMENT-REQUIRED",- HeaderValue::from_str(- &base64::engine::general_purpose::STANDARD- .encode(serde_json::to_vec(&challenge).unwrap()),- )- .unwrap(),- );- headers-}--/// With no wallet set up, the failure must surface from the *wallet seam* —-/// proving the facade reached the crate's budget check, the crate reached its-/// payment builder, and the builder reached the host signer — and read exactly-/// as it did before the flow moved into the crate.-#[tokio::test]-async fn a_payment_reaches_the_host_wallet_through_the_crate() {- let _wallet_lock = crate::web3::wallet::test_support::TEST_LOCK.lock().await;- let temp = tempfile::tempdir().unwrap();- let _workspace = crate::web3::wallet::test_support::set_workspace_env_for_test(&temp).await;- super::super::init_ledger(temp.path(), "seam-test");-- let err =- super::super::handle_402_and_pay(&solana_challenge_headers(), "https://x402.example.test")- .await- .unwrap_err();-- match err {- X402Error::Wallet(message) => {- assert!(message.starts_with("wallet secret: "), "{message}");- assert!(- message.contains(crate::web3::wallet::WALLET_NOT_CONFIGURED_MESSAGE),- "{message}"- );- }- other => panic!("expected a wallet error, got {other}"),- }-}--#[tokio::test]-async fn the_signer_reports_a_missing_wallet_for_either_chain() {- let _wallet_lock = crate::web3::wallet::test_support::TEST_LOCK.lock().await;- let temp = tempfile::tempdir().unwrap();- let _workspace = crate::web3::wallet::test_support::set_workspace_env_for_test(&temp).await;-- for chain in [PaymentChain::Solana, PaymentChain::Evm] {- let err = WalletPaymentSigner.account(chain).await.unwrap_err();- assert!(err.starts_with("wallet secret: "), "{err}");- let err = WalletPaymentSigner- .sign(chain, b"message", SignScheme::Ed25519)- .await- .unwrap_err();- assert!(err.starts_with("wallet secret: "), "{err}");- }-}--#[tokio::test]-async fn the_payment_builder_is_object_safe_for_the_facade() {- let _builder: Box<dyn PaymentBuilder> = Box::new(payments());-}--// ----------------------------------------------------------------------------// The thread seam: which chat thread a payment belongs to-// -----------------------------------------------------------------------------fn chat_ctx(thread: &str) -> crate::security::approval::ApprovalChatContext {- crate::security::approval::ApprovalChatContext {- thread_id: format!("thread-{thread}"),- client_id: format!("client-{thread}"),- request_id: None,- }-}--/// The ledger records a payment's thread from this read. If it stopped reading-/// `APPROVAL_CHAT_CONTEXT`, every tool payment would silently lose its thread.-#[tokio::test]-async fn the_thread_scope_reads_the_approval_chat_context_task_local() {- use tinywallet_x402::thread::ThreadScope;-- assert_eq!(- TaskLocalThread.current_thread(),- None,- "outside a chat turn there is no thread"- );-- let inside = crate::security::approval::APPROVAL_CHAT_CONTEXT- .scope(chat_ctx("a"), async { TaskLocalThread.current_thread() })- .await;- assert_eq!(inside.as_deref(), Some("thread-a"));-- // Nested scopes answer with the innermost thread, and the outer one is- // restored afterwards.- let (inner, outer) = crate::security::approval::APPROVAL_CHAT_CONTEXT- .scope(chat_ctx("outer"), async {- let inner = crate::security::approval::APPROVAL_CHAT_CONTEXT- .scope(chat_ctx("inner"), async {- TaskLocalThread.current_thread()- })- .await;- (inner, TaskLocalThread.current_thread())- })- .await;- assert_eq!(inner.as_deref(), Some("thread-inner"));- assert_eq!(outer.as_deref(), Some("thread-outer"));-}