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
feat(wallet): run native wallet operations through module
Steven Enamakel899b57912597
diff --git a/Cargo.lock b/Cargo.lockindex 8d68d4b898..256cc2db65 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -4281,6 +4281,7 @@ dependencies = ["tinyvoice-bus","tinywallet","tinywallet-bus",+ "tinywallet-crypto","tinywallet-web3","tinywallet-x402","tokio",@@ -7645,7 +7646,7 @@ dependencies = [[[package]]name = "tinywallet"-version = "0.8.0"+version = "0.13.0"dependencies = ["coins-bip32","coins-bip39",@@ -7663,16 +7664,16 @@ dependencies = [[[package]]name = "tinywallet-bus"-version = "0.8.0"+version = "0.13.0"dependencies = ["serde",- "tinywallet-crypto",- "tinywallet-x402",+ "serde_json",+ "thiserror 2.0.20",][[package]]name = "tinywallet-crypto"-version = "0.8.0"+version = "0.13.0"dependencies = ["async-trait","bech32 0.12.0",@@ -7683,11 +7684,12 @@ dependencies = ["sha2 0.11.0","sha3 0.12.0","thiserror 2.0.20",+ "tinywallet-bus",][[package]]name = "tinywallet-web3"-version = "0.8.0"+version = "0.13.0"dependencies = ["anyhow","async-trait",@@ -7708,7 +7710,7 @@ dependencies = [[[package]]name = "tinywallet-x402"-version = "0.8.0"+version = "0.13.0"dependencies = ["anyhow","async-trait",@@ -7725,6 +7727,7 @@ dependencies = ["sha3 0.12.0","thiserror 2.0.20","tinytools",+ "tinywallet-bus","tinywallet-crypto","uuid",]diff --git a/crates/openhuman-core/Cargo.toml b/crates/openhuman-core/Cargo.tomlindex c1ee647457..dc760c0a98 100644--- a/crates/openhuman-core/Cargo.toml+++ b/crates/openhuman-core/Cargo.toml@@ -527,6 +527,10 @@ tinyhosts-bus = { path = "../../vendor/tinyhosts/crates/tinyhosts-bus", optional# 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.@@ -801,6 +805,7 @@ 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/modules/host.rs b/crates/openhuman-core/src/modules/host.rsindex 0b91d873e7..96a5f99f40 100644--- a/crates/openhuman-core/src/modules/host.rs+++ b/crates/openhuman-core/src/modules/host.rs@@ -186,6 +186,8 @@ async fn build_runtime() -> tinybus::Result<ModuleRuntime> {let connection = Connection::connect(transport.connect().await?).await?;super::tokenjuice_host::install(&connection).await?;+ #[cfg(feature = "web3")]+ super::wallet_host::install(&connection).await?;Ok(ModuleRuntime {host,diff --git a/crates/openhuman-core/src/modules/host_tests.rs b/crates/openhuman-core/src/modules/host_tests.rsindex 9c8adc52d6..a2d8500c36 100644--- a/crates/openhuman-core/src/modules/host_tests.rs+++ b/crates/openhuman-core/src/modules/host_tests.rs@@ -26,3 +26,24 @@ async fn the_module_bus_is_a_singleton_and_serves_proxies() {// A name that cannot be a bus name is refused without reaching the bus.assert!(first.proxy("not a bus name", "/nope").is_err());}++#[cfg(feature = "web3")]+#[tokio::test]+async fn wallet_host_callback_is_served_before_the_module_is_loaded() {+ let runtime = runtime().await.expect("runtime should start");+ let proxy = runtime+ .proxy(+ tinywallet_bus::HOST_INTERFACE,+ tinywallet_bus::HOST_OBJECT_PATH,+ )+ .expect("wallet callback contract names are valid");++ let response: tinywallet_bus::wire::HostResponse = proxy+ .call(tinywallet_bus::names::host_methods::WALLET_ACCOUNTS, ())+ .await+ .expect("the host must serve callbacks before resolving the wallet module");+ assert!(matches!(+ response,+ tinywallet_bus::wire::HostResponse::WalletAccounts(_)+ ));+}diff --git a/crates/openhuman-core/src/modules/mod.rs b/crates/openhuman-core/src/modules/mod.rsindex 9e1b7e1338..921e0f7cf3 100644--- a/crates/openhuman-core/src/modules/mod.rs+++ b/crates/openhuman-core/src/modules/mod.rs@@ -82,6 +82,10 @@ pub mod voice;#[cfg(feature = "web3")]#[cfg(feature = "modules")]pub mod wallet;+#[cfg(feature = "web3")]+mod wallet_host;+#[cfg(feature = "web3")]+pub(crate) mod wallet_service;#[cfg(feature = "modules")]pub use ops::{ensure_loaded, ensure_loaded_within, state_of, LoadError};diff --git a/crates/openhuman-core/src/modules/registry/records_docs_wallet.rs b/crates/openhuman-core/src/modules/registry/records_docs_wallet.rsindex 0933a0daa6..fd825aa5d2 100644--- a/crates/openhuman-core/src/modules/registry/records_docs_wallet.rs+++ b/crates/openhuman-core/src/modules/registry/records_docs_wallet.rs@@ -74,7 +74,7 @@ pub(crate) const TINYDOCS: ModuleRecord = ModuleRecord {load: LoadPolicy::Lazy,};-/// The `tinywallet` module: transaction building and assembly for four chains.+/// The `tinywallet` module: native wallet, Web3 quote, and x402 operations.////// Lazy for the same reason as [`TINYDOCS`], and more so: most sessions never/// touch a wallet, and this artifact carries `bitcoin` and a native `secp256k1`@@ -82,10 +82,11 @@ pub(crate) const TINYDOCS: ModuleRecord = ModuleRecord {////// **This host sends it the recovery phrase, over confidential calls, and never/// derives or signs itself.** All four chains — Bitcoin, EVM, Solana and Tron —-/// derive and sign inside the module. This binary does not link the root-/// `tinywallet` crate at all — it takes `tinywallet-bus`, the wire contract,-/// which carries no `key` gate — nor does it link `k256`; see the note on the-/// `tinywallet-bus` dependency.+/// derive and sign inside the module. Web3 quotes and x402 payments, budgets,+/// and ledger state also live there. The host supplies credential custody,+/// authenticated transports, and exact-facts approval callbacks. This binary+/// depends on `tinywallet-bus` for the wire contract rather than implementation+/// crates.////// The phrase is only sent to a module tinybus has attested *and* whose digest/// matches one of the entries below — `super::wallet::attested_proxy` checks@@ -94,78 +95,101 @@ pub(crate) const TINYDOCS: ModuleRecord = ModuleRecord {/// The contract also exposes `ExportKey` for downstream hosts that must drive/// a signer locally; OpenHuman itself does not call it.///-/// Three releases got here, and the order mattered. v0.2.3 changed no method at-/// all — it was the same module rebuilt against a bus that could attest it.-/// Attestation used to be recorded only from a `modules.toml` beside the-/// artifact, and a release download extracts into a temporary directory that has-/// none, so this module could never be an attested recipient however carefully-/// the digest below was pinned (tinybus#15 fixed that). Only then was it safe-/// for v0.3.0 to add methods that take a secret, and for v0.4.0 to add-/// `SignMessage` for the Solana and x402 encodings the wire contract does not-/// model. Adding them earlier would have made them unreachable in production and-/// reachable in a developer's tree, which is the worst of both.+/// The pinned v0.13.0 release carries the native wallet, Web3, and x402 bus+/// operations. Secret-bearing operations remain confidential and require both+/// attestation and a matching pinned digest.pub(crate) const TINYWALLET: ModuleRecord = ModuleRecord {id: "tinywallet",description: "Transaction building and assembly for Bitcoin, EVM, Solana and Tron",bus_name: "ai.tinyhumans.tinywallet.Wallet",object_path: "/ai/tinyhumans/tinywallet/Wallet",- version: "0.8.0",- release_url: "https://github.com/tinyhumansai/tinywallet/releases/tag/v0.8.0",+ version: "0.13.0",+ release_url: "https://github.com/tinyhumansai/tinywallet/releases/tag/v0.13.0",assets: &[PlatformAsset {host_key: "ubuntu-24.04-x86_64",- archive: "tinywallet-module-0.8.0-ubuntu-24.04-x86_64.tar.gz",- sha256: "401d9fb2491030907c58778216bafbc78130fe8a486106faaa86432ff22a2bae",+ archive: "tinywallet-module-0.13.0-ubuntu-24.04-x86_64.tar.gz",+ sha256: "284983d01c548109b3e9d5bbca1951787912f713b4a98920b9b45cfd034b6760",},PlatformAsset {host_key: "ubuntu-24.04-arm64",- archive: "tinywallet-module-0.8.0-ubuntu-24.04-arm64.tar.gz",- sha256: "0444ff0cad34ac0aa7e26a18a84737ca48193b7f6a1452930dcba3e413174b4a",+ archive: "tinywallet-module-0.13.0-ubuntu-24.04-arm64.tar.gz",+ sha256: "18ef8ffe518f731dc594d1606554ca12c840219e54f230382937061c395ab860",},PlatformAsset {host_key: "ubuntu-22.04-x86_64",- archive: "tinywallet-module-0.8.0-ubuntu-22.04-x86_64.tar.gz",- sha256: "c16f2fdefe1f032e89d68969ccbde762ae17dde85ee1aa0248f7820852ac1008",+ archive: "tinywallet-module-0.13.0-ubuntu-22.04-x86_64.tar.gz",+ sha256: "92d0d0fe9ab20fdf4c44aa58d762b7e28b6a08876899a5b2d368df3feabcd2d5",},PlatformAsset {host_key: "ubuntu-22.04-arm64",- archive: "tinywallet-module-0.8.0-ubuntu-22.04-arm64.tar.gz",- sha256: "690c99b72655e13aaa1a307e599dff09f77e5470101fbf3331d321d787805885",+ archive: "tinywallet-module-0.13.0-ubuntu-22.04-arm64.tar.gz",+ sha256: "4d0e17d778c0c84df17e4c5b7fa60aa9296efecc5726902008946409b3a3c9e1",},PlatformAsset {host_key: "macos-26-arm64",- archive: "tinywallet-module-0.8.0-macos-26-arm64.tar.gz",- sha256: "206e74e88011a7810c88375d96082f1a85036f3d10194aedbc1513d2fe4a39a7",+ archive: "tinywallet-module-0.13.0-macos-26-arm64.tar.gz",+ sha256: "e01a70efbcece8e134abfa84c70181425802415525303d7ba2a7798afbab1041",},PlatformAsset {host_key: "macos-26-x86_64",- archive: "tinywallet-module-0.8.0-macos-26-x86_64.tar.gz",- sha256: "d4163442c6fdeada5b56a1b08b92d22ff77ec3b21634bff61ac8bf0de1bee1a0",+ archive: "tinywallet-module-0.13.0-macos-26-x86_64.tar.gz",+ sha256: "c48f1f7807d0b25c2b54dca97237f6e64d02ec3a9396370cd8e3b1857419296a",},PlatformAsset {host_key: "macos-15-arm64",- archive: "tinywallet-module-0.8.0-macos-15-arm64.tar.gz",- sha256: "a27f04db2652b09e4b855cb9ba17c9fda90ea65b0eeda6335f78fb9839a5b681",+ archive: "tinywallet-module-0.13.0-macos-15-arm64.tar.gz",+ sha256: "95f69f2e17ff1785d032f6e1017e12de5c6dc09af9633e67fc9c225dfcef9ce6",},PlatformAsset {host_key: "macos-15-x86_64",- archive: "tinywallet-module-0.8.0-macos-15-x86_64.tar.gz",- sha256: "6778db75763d9f7058228f6beeb75af04b2d2bd74d38b8109e4e310a2dfaca77",+ archive: "tinywallet-module-0.13.0-macos-15-x86_64.tar.gz",+ sha256: "f3114694e2d666ea1b030db952c589f08d79c60ab79aadb844327e273c5faaf5",},PlatformAsset {host_key: "windows-2025-x86_64",- archive: "tinywallet-module-0.8.0-windows-2025-x86_64.zip",- sha256: "48ed01c962dfd4ff35010a858f7663105cce9b24179f7e230c472742b63a3e70",+ archive: "tinywallet-module-0.13.0-windows-2025-x86_64.zip",+ sha256: "7b79a25a1fccef17a4c6e0d400f49646c3a5f321821bb03ddc23e76d6030717a",},PlatformAsset {host_key: "windows-2022-x86_64",- archive: "tinywallet-module-0.8.0-windows-2022-x86_64.zip",- sha256: "8010a390a9b27e28ac0e384f398b101f80980bc477312d5055bbb3edacf36e80",+ archive: "tinywallet-module-0.13.0-windows-2022-x86_64.zip",+ sha256: "0b7126be04b23dd5fad883d7f1dd33dd65c1042af68f93593590ea07c5daa95e",},PlatformAsset {host_key: "windows-11-arm64",- archive: "tinywallet-module-0.8.0-windows-11-arm64.zip",- sha256: "d9e685d709755c52f4ba6d1d852da5b237a19f405de95389d8650ba54e231045",+ archive: "tinywallet-module-0.13.0-windows-11-arm64.zip",+ sha256: "483d3fda2c46de71c8efd5dfa4ec828c0b6c86bb164c8362c1356f85cb8ec231",+ },+ PlatformAsset {+ host_key: "archlinux-arm64",+ archive: "tinywallet-module-0.13.0-archlinux-arm64.tar.gz",+ sha256: "ad2222bd1d2dd680568f486e40389c0b963cf5ba2d170f9d658985f31cabb511",+ },+ PlatformAsset {+ host_key: "archlinux-x86_64",+ archive: "tinywallet-module-0.13.0-archlinux-x86_64.tar.gz",+ sha256: "d67f541330f7712106238b90d993550d2e2e55f33d3c8c9f50669a1a51c1e981",+ },+ PlatformAsset {+ host_key: "fedora-43-arm64",+ archive: "tinywallet-module-0.13.0-fedora-43-arm64.tar.gz",+ sha256: "a2d62b03f2e99008ee3fe7ea84290fd050e12016ce36e89fda24d5449e795261",+ },+ PlatformAsset {+ host_key: "fedora-43-x86_64",+ archive: "tinywallet-module-0.13.0-fedora-43-x86_64.tar.gz",+ sha256: "0c8c5dbf2aa7b7caa371aa6366c7cfdd232fda41e2dbd894d2ef344c7c2cfa0a",+ },+ PlatformAsset {+ host_key: "fedora-44-arm64",+ archive: "tinywallet-module-0.13.0-fedora-44-arm64.tar.gz",+ sha256: "272b535910fc4bc84099887b7ccfbdd9d41a6d187616086c174f86cb77f21757",+ },+ PlatformAsset {+ host_key: "fedora-44-x86_64",+ archive: "tinywallet-module-0.13.0-fedora-44-x86_64.tar.gz",+ sha256: "3dcad60a65d4f0bbb1af838468a2f52d648d22b2fbc849ae0548a30ed9806646",},],load: LoadPolicy::Lazy,diff --git a/crates/openhuman-core/src/modules/registry_tests.rs b/crates/openhuman-core/src/modules/registry_tests.rsindex 8394b41071..aff88ddd65 100644--- a/crates/openhuman-core/src/modules/registry_tests.rs+++ b/crates/openhuman-core/src/modules/registry_tests.rs@@ -19,6 +19,110 @@ fn tinycomputer_registry_matches_bus_contract_and_published_release() {);}+#[test]+fn tinywallet_registry_matches_the_verified_v013_release_manifest() {+ let wallet = find("tinywallet").expect("compiled TinyWallet module");+ assert_eq!(wallet.version, "0.13.0");+ assert_eq!(+ wallet.release_url,+ "https://github.com/tinyhumansai/tinywallet/releases/tag/v0.13.0"+ );++ let actual = wallet+ .assets+ .iter()+ .map(|asset| (asset.host_key, asset.archive, asset.sha256))+ .collect::<Vec<_>>();+ let published = [+ (+ "ubuntu-24.04-x86_64",+ "tinywallet-module-0.13.0-ubuntu-24.04-x86_64.tar.gz",+ "284983d01c548109b3e9d5bbca1951787912f713b4a98920b9b45cfd034b6760",+ ),+ (+ "ubuntu-24.04-arm64",+ "tinywallet-module-0.13.0-ubuntu-24.04-arm64.tar.gz",+ "18ef8ffe518f731dc594d1606554ca12c840219e54f230382937061c395ab860",+ ),+ (+ "ubuntu-22.04-x86_64",+ "tinywallet-module-0.13.0-ubuntu-22.04-x86_64.tar.gz",+ "92d0d0fe9ab20fdf4c44aa58d762b7e28b6a08876899a5b2d368df3feabcd2d5",+ ),+ (+ "ubuntu-22.04-arm64",+ "tinywallet-module-0.13.0-ubuntu-22.04-arm64.tar.gz",+ "4d0e17d778c0c84df17e4c5b7fa60aa9296efecc5726902008946409b3a3c9e1",+ ),+ (+ "macos-26-arm64",+ "tinywallet-module-0.13.0-macos-26-arm64.tar.gz",+ "e01a70efbcece8e134abfa84c70181425802415525303d7ba2a7798afbab1041",+ ),+ (+ "macos-26-x86_64",+ "tinywallet-module-0.13.0-macos-26-x86_64.tar.gz",+ "c48f1f7807d0b25c2b54dca97237f6e64d02ec3a9396370cd8e3b1857419296a",+ ),+ (+ "macos-15-arm64",+ "tinywallet-module-0.13.0-macos-15-arm64.tar.gz",+ "95f69f2e17ff1785d032f6e1017e12de5c6dc09af9633e67fc9c225dfcef9ce6",+ ),+ (+ "macos-15-x86_64",+ "tinywallet-module-0.13.0-macos-15-x86_64.tar.gz",+ "f3114694e2d666ea1b030db952c589f08d79c60ab79aadb844327e273c5faaf5",+ ),+ (+ "windows-2025-x86_64",+ "tinywallet-module-0.13.0-windows-2025-x86_64.zip",+ "7b79a25a1fccef17a4c6e0d400f49646c3a5f321821bb03ddc23e76d6030717a",+ ),+ (+ "windows-2022-x86_64",+ "tinywallet-module-0.13.0-windows-2022-x86_64.zip",+ "0b7126be04b23dd5fad883d7f1dd33dd65c1042af68f93593590ea07c5daa95e",+ ),+ (+ "windows-11-arm64",+ "tinywallet-module-0.13.0-windows-11-arm64.zip",+ "483d3fda2c46de71c8efd5dfa4ec828c0b6c86bb164c8362c1356f85cb8ec231",+ ),+ (+ "archlinux-arm64",+ "tinywallet-module-0.13.0-archlinux-arm64.tar.gz",+ "ad2222bd1d2dd680568f486e40389c0b963cf5ba2d170f9d658985f31cabb511",+ ),+ (+ "archlinux-x86_64",+ "tinywallet-module-0.13.0-archlinux-x86_64.tar.gz",+ "d67f541330f7712106238b90d993550d2e2e55f33d3c8c9f50669a1a51c1e981",+ ),+ (+ "fedora-43-arm64",+ "tinywallet-module-0.13.0-fedora-43-arm64.tar.gz",+ "a2d62b03f2e99008ee3fe7ea84290fd050e12016ce36e89fda24d5449e795261",+ ),+ (+ "fedora-43-x86_64",+ "tinywallet-module-0.13.0-fedora-43-x86_64.tar.gz",+ "0c8c5dbf2aa7b7caa371aa6366c7cfdd232fda41e2dbd894d2ef344c7c2cfa0a",+ ),+ (+ "fedora-44-arm64",+ "tinywallet-module-0.13.0-fedora-44-arm64.tar.gz",+ "272b535910fc4bc84099887b7ccfbdd9d41a6d187616086c174f86cb77f21757",+ ),+ (+ "fedora-44-x86_64",+ "tinywallet-module-0.13.0-fedora-44-x86_64.tar.gz",+ "3dcad60a65d4f0bbb1af838468a2f52d648d22b2fbc849ae0548a30ed9806646",+ ),+ ];+ assert_eq!(actual, published);+}+#[test]fn tinybox_registry_matches_the_published_v0118_release_manifest() {let record = find("tinybox").expect("compiled TinyBox module");diff --git a/crates/openhuman-core/src/modules/wallet.rs b/crates/openhuman-core/src/modules/wallet.rsindex 562b9c3577..1e77eb33d9 100644--- a/crates/openhuman-core/src/modules/wallet.rs+++ b/crates/openhuman-core/src/modules/wallet.rs@@ -66,6 +66,8 @@//! with which it is, and [`sign_payload`] dispatches on the tag rather than on//! the chain — so a chain that changes scheme cannot silently sign wrongly.+use serde::de::DeserializeOwned;+use serde::Serialize;use tinywallet_bus::names::methods;use tinywallet_bus::wire::{DerivedAccount, ExportRequest, ExportedKey, Scheme, SecretMaterial, SignMessageRequest,@@ -221,6 +223,42 @@ pub async fn export_key(.map_err(|error| classify(&error))}+/// Call a typed Wallet, Web3, or x402 member with one request argument.+/// Business rules stay in the module; the host only transports the request.+pub async fn call<Request, Reply>(+ config: &Config,+ member: &str,+ request: Request,+) -> Result<Reply, WalletCallError>+where+ Request: Serialize + Send,+ Reply: DeserializeOwned,+{+ let (runtime, record) = ready(config).await?;+ proxy(runtime, record)?+ .call::<Reply>(member, (request,))+ .await+ .map_err(|error| classify(&error))+}++/// Call a Wallet member carrying secret material over TinyBus's confidential+/// transport. The loaded module must be attested and match this build's pin.+pub async fn call_confidential<Request, Reply>(+ config: &Config,+ member: &str,+ request: &Request,+) -> Result<Reply, WalletCallError>+where+ Request: Serialize + Send,+ Reply: DeserializeOwned,+{+ attested_proxy(config)+ .await?+ .call_confidential::<Reply>(member, (request,))+ .await+ .map_err(|error| classify(&error))+}+/// A proxy that has proved it is the artifact this build pinned.////// # Why check here when the broker already refusesdiff --git a/crates/openhuman-core/src/modules/wallet_host.rs b/crates/openhuman-core/src/modules/wallet_host.rsnew file mode 100644index 0000000000..b869a9ef7e--- /dev/null+++ b/crates/openhuman-core/src/modules/wallet_host.rs@@ -0,0 +1,562 @@+//! OpenHuman's typed host callbacks for the loadable TinyWallet module.+//!+//! The wallet module owns network/quote/payment algorithms and signing. This+//! service supplies only current public account facts, endpoint-backed chain+//! transport, authenticated wallet-backend transport, and a confirmation+//! decision bound to an in-flight confirmed execution request.++use std::collections::{HashMap, HashSet};+use std::future::Future;+use std::sync::{Mutex, OnceLock};++use tinybus::ObjectPath;+use tinywallet_bus::wire::{+ AuthorizationResult, AuthorizeNativeWalletExecutionRequest, AuthorizeWeb3ExecutionRequest,+ AuthorizeX402PaymentRequest, ChainTransportRequest, ChainTransportResult, HostResponse,+ WalletAccountInfo, WalletAccountsResponse, WalletBackendRequest, WalletBackendResponse,+};+use tinywallet_crypto::rpc::{NetworkId, Transport, TransportError};++const HOST_ERROR_NAME: &str = "ai.tinyhumans.tinywallet.Host.Error.CallbackFailed";++#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]+pub(crate) enum ApprovalKind {+ Native,+ Web3,+}++#[derive(Debug, Clone, PartialEq, Eq, Hash)]+struct ApprovalKey {+ kind: ApprovalKind,+ quote_id: String,+}++static APPROVALS: OnceLock<Mutex<HashSet<ApprovalKey>>> = OnceLock::new();+static NATIVE_APPROVAL_QUOTES: OnceLock<+ Mutex<HashMap<String, tinywallet_bus::wire::PreparedTransaction>>,+> = OnceLock::new();+static ENDPOINT_REFERENCES: OnceLock<+ Mutex<HashMap<String, (tinywallet_bus::wire::RpcEndpointKey, String)>>,+> = OnceLock::new();++fn approvals() -> &'static Mutex<HashSet<ApprovalKey>> {+ APPROVALS.get_or_init(|| Mutex::new(HashSet::new()))+}++fn native_approval_quotes(+) -> &'static Mutex<HashMap<String, tinywallet_bus::wire::PreparedTransaction>> {+ NATIVE_APPROVAL_QUOTES.get_or_init(|| Mutex::new(HashMap::new()))+}++fn endpoint_references(+) -> &'static Mutex<HashMap<String, (tinywallet_bus::wire::RpcEndpointKey, String)>> {+ ENDPOINT_REFERENCES.get_or_init(|| Mutex::new(HashMap::new()))+}++/// Bind module-issued opaque endpoint aliases to the current host configuration.+/// Actual URLs remain in this process and are never serialized onto TinyBus.+pub(crate) fn bind_endpoint_references(+ configured: &tinywallet_bus::wire::NativeWalletConfigResponse,+) -> Result<(), String> {+ use tinywallet_bus::wire::RpcEndpointKey;++ let mut resolved = HashMap::new();+ for endpoint in &configured.endpoint_references {+ let url = match endpoint.key {+ RpcEndpointKey::Evm { network } => {+ crate::web3::wallet::endpoints::rpc_url_for_evm_network(network)+ }+ RpcEndpointKey::Btc => crate::web3::wallet::endpoints::rpc_url_for_chain(+ crate::web3::wallet::WalletChain::Btc,+ ),+ RpcEndpointKey::Solana => crate::web3::wallet::endpoints::rpc_url_for_chain(+ crate::web3::wallet::WalletChain::Solana,+ ),+ RpcEndpointKey::Tron => crate::web3::wallet::endpoints::rpc_url_for_chain(+ crate::web3::wallet::WalletChain::Tron,+ ),+ };+ if endpoint.reference.trim().is_empty()+ || resolved+ .insert(endpoint.reference.clone(), (endpoint.key, url))+ .is_some()+ {+ return Err("wallet module returned an invalid endpoint reference".into());+ }+ }+ *endpoint_references()+ .lock()+ .map_err(|_| "wallet endpoint reference store is unavailable".to_string())? = resolved;+ Ok(())+}++pub(crate) fn clear_endpoint_references() {+ if let Ok(mut references) = endpoint_references().lock() {+ references.clear();+ }+}++pub(crate) async fn wallet_accounts_snapshot(+) -> Result<tinywallet_bus::wire::WalletAccountsResponse, String> {+ let status = crate::web3::wallet::status()+ .await+ .map_err(|error| error.to_string())?+ .value;+ let accounts = status+ .accounts+ .into_iter()+ .map(|account| WalletAccountInfo {+ chain: account.chain.to_chain(),+ address: account.address,+ derivation_path: account.derivation_path,+ })+ .collect();+ Ok(WalletAccountsResponse {+ configured: status.configured,+ accounts,+ })+}++/// One-shot authorization permit for an execution whose public RPC request+/// already carried `confirmed: true`.+struct ApprovalPermit(ApprovalKey);++impl ApprovalPermit {+ fn new(+ kind: ApprovalKind,+ quote_id: &str,+ expected_native_quote: Option<tinywallet_bus::wire::PreparedTransaction>,+ ) -> Self {+ let key = ApprovalKey {+ kind,+ quote_id: quote_id.to_owned(),+ };+ if let Ok(mut active) = approvals().lock() {+ active.insert(key.clone());+ }+ if kind == ApprovalKind::Native {+ if let (Some(quote), Ok(mut active)) =+ (expected_native_quote, native_approval_quotes().lock())+ {+ active.insert(quote_id.to_owned(), quote);+ }+ }+ Self(key)+ }+}++impl Drop for ApprovalPermit {+ fn drop(&mut self) {+ if let Ok(mut active) = approvals().lock() {+ active.remove(&self.0);+ }+ if self.0.kind == ApprovalKind::Native {+ if let Ok(mut active) = native_approval_quotes().lock() {+ active.remove(&self.0.quote_id);+ }+ }+ }+}++fn consume_approval(kind: ApprovalKind, quote_id: &str) -> bool {+ approvals().lock().is_ok_and(|mut active| {+ active.remove(&ApprovalKey {+ kind,+ quote_id: quote_id.to_owned(),+ })+ })+}++pub(super) fn native_approval_matches_request(+ expected_quote: &tinywallet_bus::wire::PreparedTransaction,+ request: &tinywallet_bus::wire::AuthorizeNativeWalletExecutionRequest,+) -> bool {+ let permit = consume_approval(ApprovalKind::Native, &request.quote_id);+ permit+ && expected_quote.quote_id == request.quote_id+ && expected_quote == &request.quote+ && request.operation == "transfer"+ && native_intent_matches_quote(expected_quote, &request.intent)+}++fn native_intent_matches_quote(+ quote: &tinywallet_bus::wire::PreparedTransaction,+ intent: &tinywallet_bus::wire::NativeWalletExecutionIntent,+) -> bool {+ use tinywallet_bus::wire::{+ NativeWalletExecutionIntent, PreparedKind, TransactionSpec, WalletChain,+ };++ match intent {+ NativeWalletExecutionIntent::Transaction { transaction } => match transaction {+ TransactionSpec::Btc {+ from,+ to,+ amount_sat,+ ..+ } => {+ quote.chain == WalletChain::Btc+ && quote.kind == PreparedKind::NativeTransfer+ && from == "e.from_address+ && to == "e.to_address+ && quote.amount_raw.parse::<u64>().ok() == Some(*amount_sat)+ }+ TransactionSpec::Evm {+ to,+ value_wei,+ data_hex,+ chain_id,+ ..+ } => {+ let network = quote+ .evm_network+ .unwrap_or(tinywallet_bus::wire::EvmNetwork::EthereumMainnet);+ if quote.chain != WalletChain::Evm || network.chain_id() != *chain_id {+ return false;+ }+ match quote.kind {+ PreparedKind::NativeTransfer => {+ to == "e.to_address+ && value_wei == "e.amount_raw+ && data_hex.is_empty()+ }+ PreparedKind::TokenTransfer => {+ let Some(contract) = quote.token_address.as_deref() else {+ return false;+ };+ to.eq_ignore_ascii_case(contract)+ && value_wei == "0"+ && evm_transfer_data_matches(+ data_hex,+ "e.to_address,+ "e.amount_raw,+ )+ }+ }+ }+ TransactionSpec::Solana {+ from, to, lamports, ..+ } => {+ quote.chain == WalletChain::Solana+ && quote.kind == PreparedKind::NativeTransfer+ && from == "e.from_address+ && to == "e.to_address+ && quote.amount_raw.parse::<u64>().ok() == Some(*lamports)+ }+ TransactionSpec::Tron {+ expected_to,+ transfer,+ ..+ } => {+ use tinywallet_bus::TronTransfer;+ if quote.chain != WalletChain::Tron || expected_to != "e.to_address {+ return false;+ }+ match (quote.kind, transfer) {+ (PreparedKind::NativeTransfer, TronTransfer::Native { amount_sun }) => {+ quote.amount_raw.parse::<u64>().ok() == Some(*amount_sun)+ }+ (PreparedKind::TokenTransfer, TronTransfer::Trc20 { parameter_hex }) => {+ valid_hex(parameter_hex)+ }+ _ => false,+ }+ }+ _ => false,+ },+ NativeWalletExecutionIntent::SolanaMessage { message_hex } => {+ quote.chain == WalletChain::Solana+ && quote.kind == PreparedKind::TokenTransfer+ && valid_hex(message_hex)+ }+ }+}++fn evm_transfer_data_matches(data: &str, recipient: &str, amount: &str) -> bool {+ let Some(address) = recipient+ .strip_prefix("0x")+ .or_else(|| recipient.strip_prefix("0X"))+ else {+ return false;+ };+ if address.len() != 40 || !address.bytes().all(|byte| byte.is_ascii_hexdigit()) {+ return false;+ }+ let Some(amount_word) = decimal_u256_word(amount) else {+ return false;+ };+ let expected = format!("a9059cbb{:0>64}{amount_word}", address.to_ascii_lowercase());+ let actual = data+ .strip_prefix("0x")+ .or_else(|| data.strip_prefix("0X"))+ .unwrap_or(data);+ actual.eq_ignore_ascii_case(&expected)+}++fn decimal_u256_word(decimal: &str) -> Option<String> {+ if decimal.is_empty() || !decimal.bytes().all(|byte| byte.is_ascii_digit()) {+ return None;+ }+ let mut bytes = [0u8; 32];+ for digit in decimal.bytes().map(|byte| byte - b'0') {+ let mut carry = u16::from(digit);+ for byte in bytes.iter_mut().rev() {+ let value = u16::from(*byte) * 10 + carry;+ *byte = (value & 0xff) as u8;+ carry = value >> 8;+ }+ if carry != 0 {+ return None;+ }+ }+ Some(bytes.iter().map(|byte| format!("{byte:02x}")).collect())+}++fn valid_hex(value: &str) -> bool {+ !value.is_empty()+ && value.len().is_multiple_of(2)+ && value.bytes().all(|byte| byte.is_ascii_hexdigit())+}++/// Keep the confirmation permit alive only while the corresponding module+/// execution is in flight. The callback consumes it once and is correlated by+/// the immutable module-issued quote id.+pub(crate) async fn with_confirmed_execution<F: Future>(+ kind: ApprovalKind,+ quote_id: &str,+ expected_native_quote: Option<tinywallet_bus::wire::PreparedTransaction>,+ future: F,+) -> F::Output {+ let _permit = ApprovalPermit::new(kind, quote_id, expected_native_quote);+ future.await+}++#[derive(Clone, Copy)]+struct WalletHost;++#[tinybus::interface(name = "ai.tinyhumans.tinywallet.Host")]+impl WalletHost {+ /// Public wallet setup state and addresses; encrypted secrets never leave+ /// the host's custody store through this callback.+ async fn wallet_accounts(&self) -> tinybus::Result<HostResponse> {+ Ok(HostResponse::WalletAccounts(+ wallet_accounts_snapshot().await.map_err(callback_error)?,+ ))+ }++ /// Run the chain operation through OpenHuman's configured RPC transport.+ async fn chain_transport(+ &self,+ request: ChainTransportRequest,+ ) -> tinybus::Result<HostResponse> {+ let (network, endpoint_ref, chain, evm_chain_id) = match &request {+ ChainTransportRequest::JsonRpc { network, .. }+ | ChainTransportRequest::RestGet { network, .. }+ | ChainTransportRequest::RestPost { network, .. } => (+ network_id(network.chain, network.evm_chain_id),+ network.endpoint_ref.as_deref(),+ network.chain,+ network.evm_chain_id,+ ),+ };+ let endpoint_url = match endpoint_ref {+ Some(reference) => {+ let Some((key, url)) = endpoint_references()+ .lock()+ .ok()+ .and_then(|references| references.get(reference).cloned())+ else {+ return Ok(HostResponse::ChainTransport(+ ChainTransportResult::RpcError {+ message:+ "the requested wallet endpoint reference is not active in this host"+ .into(),+ },+ ));+ };+ if Some(key) != endpoint_key(chain, evm_chain_id) {+ return Ok(HostResponse::ChainTransport(+ ChainTransportResult::RpcError {+ message:+ "the wallet endpoint reference does not match the requested network"+ .into(),+ },+ ));+ }+ Some(url)+ }+ None => None,+ };+ let transport = crate::web3::wallet::transport::OpenHumanTransport::new();+ let result = match request {+ ChainTransportRequest::JsonRpc { method, params, .. } => match endpoint_url {+ Some(url) => crate::web3::wallet::rpc::rpc_call_to::<serde_json::Value>(+ &url, &method, params,+ )+ .await+ .map_err(|message| crate::web3::wallet::transport::classify(network, message)),+ None => transport.json_rpc(network, &method, params).await,+ },+ ChainTransportRequest::RestGet { path, .. } => match endpoint_url {+ Some(url) => crate::web3::wallet::rpc::rest_get_text(&join_endpoint(&url, &path))+ .await+ .map(serde_json::Value::String)+ .map_err(|message| crate::web3::wallet::transport::classify(network, message)),+ None => transport+ .rest_get(network, &path)+ .await+ .map(serde_json::Value::String),+ },+ ChainTransportRequest::RestPost {+ path,+ body,+ content_type,+ ..+ } => match endpoint_url {+ Some(url) => crate::web3::wallet::rpc::rest_post_text(+ &join_endpoint(&url, &path),+ &body,+ &content_type,+ )+ .await+ .map(serde_json::Value::String)+ .map_err(|message| crate::web3::wallet::transport::classify(network, message)),+ None => transport+ .rest_post(network, &path, body, &content_type)+ .await+ .map(serde_json::Value::String),+ },+ };+ let response = match result {+ Ok(body) => ChainTransportResult::Ok { body },+ Err(TransportError::Unreachable { message, .. }) => {+ ChainTransportResult::Unreachable { message }+ }+ Err(TransportError::Rpc { message, .. }) => ChainTransportResult::RpcError { message },+ Err(error) => ChainTransportResult::RpcError {+ message: error.to_string(),+ },+ };+ Ok(HostResponse::ChainTransport(response))+ }++ /// Perform only the named authenticated wallet-backend request.+ async fn wallet_backend(&self, request: WalletBackendRequest) -> tinybus::Result<HostResponse> {+ let config = crate::config::rpc::load_config_with_timeout()+ .await+ .map_err(callback_error)?;+ let client =+ crate::web3::client::CryptoClient::from_config(&config).map_err(callback_error)?;+ let data = match request {+ WalletBackendRequest::Routes => client.routes().await,+ WalletBackendRequest::SwapTransaction { body } => client.swap_tx(&body).await,+ WalletBackendRequest::BridgeTransaction { body } => client.bridge_tx(&body).await,+ }+ .map_err(callback_error)?;+ Ok(HostResponse::WalletBackend(WalletBackendResponse { data }))+ }++ /// A module callback is permitted only while the host is servicing the+ /// exact confirmed quote id. The module supplies the transaction intent+ /// built from its stored quote; the host never constructs or signs it.+ async fn authorize_web3_execution(+ &self,+ request: AuthorizeWeb3ExecutionRequest,+ ) -> tinybus::Result<HostResponse> {+ Ok(HostResponse::Authorization(AuthorizationResult {+ approved: consume_approval(ApprovalKind::Web3, &request.quote_id),+ reason: None,+ }))+ }++ /// Approve the exact native quote facts only inside the corresponding+ /// confirmed host operation.+ async fn authorize_native_wallet_execution(+ &self,+ request: AuthorizeNativeWalletExecutionRequest,+ ) -> tinybus::Result<HostResponse> {+ let expected = native_approval_quotes()+ .lock()+ .ok()+ .and_then(|mut quotes| quotes.remove(&request.quote_id));+ let approved = expected+ .as_ref()+ .is_some_and(|quote| native_approval_matches_request(quote, &request));+ Ok(HostResponse::Authorization(AuthorizationResult {+ approved,+ reason: None,+ }))+ }++ /// x402 authorization is supplied by the host's guarded HTTP request path;+ /// absent an active guard scope, payment signing fails closed.+ async fn authorize_x402_payment(+ &self,+ _request: AuthorizeX402PaymentRequest,+ ) -> tinybus::Result<HostResponse> {+ Ok(HostResponse::Authorization(AuthorizationResult {+ approved: false,+ reason: Some("x402 payment has no active host authorization".into()),+ }))+ }+}++fn network_id(chain: tinywallet_bus::Chain, evm_chain_id: Option<u64>) -> NetworkId {+ if chain == tinywallet_bus::Chain::Evm {+ NetworkId {+ chain,+ evm_chain_id,+ }+ } else {+ NetworkId::chain(chain)+ }+}++fn endpoint_key(+ chain: tinywallet_bus::Chain,+ evm_chain_id: Option<u64>,+) -> Option<tinywallet_bus::wire::RpcEndpointKey> {+ use tinywallet_bus::wire::{EvmNetwork, RpcEndpointKey};+ match chain {+ tinywallet_bus::Chain::Evm => EvmNetwork::ALL+ .into_iter()+ .find(|network| Some(network.chain_id()) == evm_chain_id)+ .map(|network| RpcEndpointKey::Evm { network }),+ tinywallet_bus::Chain::Btc => Some(RpcEndpointKey::Btc),+ tinywallet_bus::Chain::Solana => Some(RpcEndpointKey::Solana),+ tinywallet_bus::Chain::Tron => Some(RpcEndpointKey::Tron),+ _ => None,+ }+}++fn join_endpoint(base: &str, path: &str) -> String {+ format!(+ "{}/{}",+ base.trim_end_matches('/'),+ path.trim_start_matches('/')+ )+}++fn callback_error(error: impl std::fmt::Display) -> tinybus::Error {+ tinybus::Error::MethodFailed {+ name: HOST_ERROR_NAME.to_string(),+ message: error.to_string(),+ }+}++/// Install the host callback interface before any TinyWallet module can load.+pub(super) async fn install(connection: &tinybus::Connection) -> tinybus::Result<()> {+ connection+ .serve_at(+ ObjectPath::new(tinywallet_bus::HOST_OBJECT_PATH)?,+ WalletHost,+ )+ .await?;+ connection+ .request_name(tinywallet_bus::HOST_INTERFACE)+ .await+}++#[cfg(test)]+#[path = "wallet_host_tests.rs"]+mod tests;diff --git a/crates/openhuman-core/src/modules/wallet_host_tests.rs b/crates/openhuman-core/src/modules/wallet_host_tests.rsnew file mode 100644index 0000000000..5caa7a1590--- /dev/null+++ b/crates/openhuman-core/src/modules/wallet_host_tests.rs@@ -0,0 +1,105 @@+use super::{consume_approval, native_approval_matches_request, ApprovalKind, ApprovalPermit};+use tinywallet_bus::wire::{+ AuthorizeNativeWalletExecutionRequest, EvmNetwork, NativeWalletExecutionIntent, PreparedKind,+ PreparedStatus, PreparedTransaction, TransactionSpec, WalletChain,+};++#[test]+fn execution_authorization_is_bound_to_one_confirmed_quote_id() {+ let permit = ApprovalPermit::new(ApprovalKind::Web3, "quote-17", None);+ assert!(!consume_approval(ApprovalKind::Web3, "quote-18"));+ assert!(!consume_approval(ApprovalKind::Native, "quote-17"));+ assert!(consume_approval(ApprovalKind::Web3, "quote-17"));+ assert!(!consume_approval(ApprovalKind::Web3, "quote-17"));+ drop(permit);+}++#[test]+fn an_unconsumed_confirmation_is_removed_when_the_execution_ends() {+ {+ let quote = native_quote("quote-cancelled");+ let _permit = ApprovalPermit::new(ApprovalKind::Native, "quote-cancelled", Some(quote));+ }+ assert!(!consume_approval(ApprovalKind::Native, "quote-cancelled"));+}++#[test]+fn native_approval_rejects_a_quote_that_differs_from_the_confirmed_quote() {+ let quote = native_quote("native-quote-facts");+ let permit = ApprovalPermit::new(ApprovalKind::Native, "e.quote_id, Some(quote.clone()));+ let mut changed_quote = quote.clone();+ changed_quote.amount_raw = "43".into();+ let request = native_request(changed_quote, "0xrecipient", "42");++ assert!(!native_approval_matches_request("e, &request));+ assert!(!consume_approval(ApprovalKind::Native, "e.quote_id));+ drop(permit);+}++#[test]+fn native_approval_rejects_signer_intent_that_changes_the_confirmed_transfer() {+ let quote = native_quote("native-quote-intent");+ let permit = ApprovalPermit::new(ApprovalKind::Native, "e.quote_id, Some(quote.clone()));+ let request = native_request(quote.clone(), "0xattacker", "42");++ assert!(!native_approval_matches_request("e, &request));+ assert!(!consume_approval(ApprovalKind::Native, "e.quote_id));+ drop(permit);+}++#[test]+fn native_approval_accepts_the_exact_confirmed_quote_and_signer_intent_once() {+ let quote = native_quote("native-quote-valid");+ let permit = ApprovalPermit::new(ApprovalKind::Native, "e.quote_id, Some(quote.clone()));+ let request = native_request(quote.clone(), "e.to_address, "e.amount_raw);++ assert!(native_approval_matches_request("e, &request));+ assert!(!consume_approval(ApprovalKind::Native, "e.quote_id));+ drop(permit);+}++fn native_quote(quote_id: &str) -> PreparedTransaction {+ PreparedTransaction {+ quote_id: quote_id.into(),+ kind: PreparedKind::NativeTransfer,+ chain: WalletChain::Evm,+ evm_network: Some(EvmNetwork::EthereumMainnet),+ from_address: "0xsender".into(),+ to_address: "0xrecipient".into(),+ asset_symbol: "ETH".into(),+ amount_raw: "42".into(),+ amount_formatted: "42".into(),+ receive_symbol: None,+ min_receive_raw: None,+ calldata: None,+ token_address: None,+ estimated_fee_raw: "1".into(),+ status: PreparedStatus::AwaitingConfirmation,+ created_at_ms: 1,+ expires_at_ms: u64::MAX,+ notes: vec![],+ }+}++fn native_request(+ quote: PreparedTransaction,+ recipient: &str,+ amount: &str,+) -> AuthorizeNativeWalletExecutionRequest {+ AuthorizeNativeWalletExecutionRequest {+ quote_id: quote.quote_id.clone(),+ operation: "transfer".into(),+ quote,+ intent: NativeWalletExecutionIntent::Transaction {+ transaction: TransactionSpec::Evm {+ to: recipient.into(),+ value_wei: amount.into(),+ data_hex: String::new(),+ nonce: 0,+ gas_limit: 21_000,+ gas_price_wei: "1".into(),+ chain_id: 1,+ },+ },+ }+}diff --git a/crates/openhuman-core/src/modules/wallet_service.rs b/crates/openhuman-core/src/modules/wallet_service.rsnew file mode 100644index 0000000000..bed6c26af2--- /dev/null+++ b/crates/openhuman-core/src/modules/wallet_service.rs@@ -0,0 +1,308 @@+//! Serialized, user-scoped access to the module-owned native wallet service.++use std::collections::HashMap;+use std::future::Future;+use std::path::PathBuf;+use std::sync::OnceLock;++use tinywallet_bus::names::methods;+use tinywallet_bus::wire::{+ EvmNetwork, NativeWalletCloseRequest, NativeWalletConfigRequest, NativeWalletConfigResponse,+ NativeWalletServiceHandle, RpcEndpointKey, SolanaCluster, WalletAccountsResponse,+};+use zeroize::Zeroize;++use crate::config::Config;++use super::wallet::{self, WalletCallError};++struct NativeWalletService {+ workspace: PathBuf,+ configuration: NativeWalletConfigRequest,+ accounts: WalletAccountsResponse,+ response: NativeWalletConfigResponse,+ prepared_quotes: HashMap<String, tinywallet_bus::wire::PreparedTransaction>,+}++static NATIVE_WALLET_SERVICE: OnceLock<tokio::sync::Mutex<Option<NativeWalletService>>> =+ OnceLock::new();++fn native_wallet_service() -> &'static tokio::sync::Mutex<Option<NativeWalletService>> {+ NATIVE_WALLET_SERVICE.get_or_init(|| tokio::sync::Mutex::new(None))+}++/// Run one operation under the current user's module service. The lock spans+/// the complete bus operation so a user or endpoint change cannot replace the+/// module's quote store while an earlier request is still using it.+pub(crate) async fn with_native_wallet<R, F, Fut>(+ config: &Config,+ operation: F,+) -> Result<R, WalletCallError>+where+ F: FnOnce(NativeWalletServiceHandle) -> Fut + Send,+ Fut: Future<Output = Result<R, WalletCallError>> + Send,+ R: Send,+{+ let mut active = native_wallet_service().lock().await;+ let accounts = super::wallet_host::wallet_accounts_snapshot()+ .await+ .map_err(WalletCallError::Failed)?;+ let configuration = native_wallet_config_request();+ let workspace = config.workspace_dir.clone();++ ensure_native_wallet(config, &mut active, workspace, configuration, accounts).await?;++ let Some(service) = active+ .as_ref()+ .map(|service| service.response.service.clone())+ else {+ return Err(WalletCallError::Failed(+ "native wallet service configuration did not produce a handle".into(),+ ));+ };+ operation(service).await+}++async fn ensure_native_wallet(+ config: &Config,+ active: &mut Option<NativeWalletService>,+ workspace: PathBuf,+ configuration: NativeWalletConfigRequest,+ accounts: WalletAccountsResponse,+) -> Result<(), WalletCallError> {+ if active.as_ref().is_some_and(|service| {+ service_requires_replacement(service, &workspace, &configuration, &accounts)+ }) {+ if let Some(service) = active.as_ref() {+ close_native_wallet(config, service).await?;+ }+ *active = None;+ }++ if active.is_none() {+ let response: NativeWalletConfigResponse = wallet::call(+ config,+ methods::NATIVE_WALLET_CONFIGURE,+ configuration.clone(),+ )+ .await?;+ if let Err(error) = super::wallet_host::bind_endpoint_references(&response) {+ let _ = wallet::call::<_, ()>(+ config,+ methods::NATIVE_WALLET_CLOSE,+ NativeWalletCloseRequest {+ service: response.service.clone(),+ },+ )+ .await;+ return Err(WalletCallError::Failed(error));+ }+ *active = Some(NativeWalletService {+ workspace,+ configuration,+ accounts,+ response,+ prepared_quotes: HashMap::new(),+ });+ }+ Ok(())+}++/// Prepare a native transfer through the module and remember only the quote's+/// chain so the host can select the correct encrypted wallet slot at execution.+pub(crate) async fn prepare_native_transfer(+ config: &Config,+ owner: Option<tinywallet_bus::wire::QuoteOwner>,+ params: tinywallet_bus::wire::PrepareTransferParams,+) -> Result<tinywallet_bus::wire::PreparedTransaction, WalletCallError> {+ let mut active = native_wallet_service().lock().await;+ let accounts = super::wallet_host::wallet_accounts_snapshot()+ .await+ .map_err(WalletCallError::Failed)?;+ ensure_native_wallet(+ config,+ &mut active,+ config.workspace_dir.clone(),+ native_wallet_config_request(),+ accounts,+ )+ .await?;+ let service = active+ .as_mut()+ .ok_or_else(|| WalletCallError::Failed("native wallet service is unavailable".into()))?;+ let quote: tinywallet_bus::wire::PreparedTransaction = wallet::call(+ config,+ methods::NATIVE_WALLET_PREPARE_TRANSFER,+ tinywallet_bus::wire::NativeWalletPrepareTransferRequest {+ service: service.response.service.clone(),+ owner,+ params,+ },+ )+ .await?;+ let now = now_ms();+ service+ .prepared_quotes+ .retain(|_, prepared| prepared.expires_at_ms > now);+ service+ .prepared_quotes+ .insert(quote.quote_id.clone(), quote.clone());+ Ok(quote)+}++/// Execute one explicitly confirmed native quote. The host retrieves only the+/// matching account secret and delivers it over the attested confidential bus+/// call; the module owns quote validation, approval facts, signing and broadcast.+pub(crate) async fn execute_native_transfer(+ config: &Config,+ owner: Option<tinywallet_bus::wire::QuoteOwner>,+ params: tinywallet_bus::wire::ExecutePreparedParams,+) -> Result<tinywallet_bus::wire::ExecutionResult, WalletCallError> {+ if !params.confirmed {+ return Err(WalletCallError::InvalidInput(+ "native wallet execution requires confirmed: true".into(),+ ));+ }++ let mut active = native_wallet_service().lock().await;+ let accounts = super::wallet_host::wallet_accounts_snapshot()+ .await+ .map_err(WalletCallError::Failed)?;+ ensure_native_wallet(+ config,+ &mut active,+ config.workspace_dir.clone(),+ native_wallet_config_request(),+ accounts,+ )+ .await?;+ let service = active+ .as_mut()+ .ok_or_else(|| WalletCallError::Failed("native wallet service is unavailable".into()))?;+ let quote = service+ .prepared_quotes+ .get(¶ms.quote_id)+ .filter(|quote| quote.expires_at_ms > now_ms())+ .cloned()+ .ok_or_else(|| {+ WalletCallError::InvalidInput("prepared wallet quote is unavailable".into())+ })?;+ let secret = signing_secret(config, quote.chain).await?;+ let mut request = tinywallet_bus::wire::NativeWalletExecuteRequest {+ service: service.response.service.clone(),+ owner,+ quote_id: params.quote_id.clone(),+ confirmed: params.confirmed,+ secret,+ };+ let result = super::wallet_host::with_confirmed_execution(+ super::wallet_host::ApprovalKind::Native,+ ¶ms.quote_id,+ Some(quote),+ wallet::call_confidential(config, methods::NATIVE_WALLET_EXECUTE_PREPARED, &request),+ )+ .await;+ request.secret.mnemonic.zeroize();+ if result.is_ok() {+ service.prepared_quotes.remove(¶ms.quote_id);+ }+ result+}++async fn signing_secret(+ config: &Config,+ chain: tinywallet_bus::wire::WalletChain,+) -> Result<tinywallet_bus::wire::SecretMaterial, WalletCallError> {+ let local_chain = match chain {+ tinywallet_bus::wire::WalletChain::Evm => crate::web3::wallet::WalletChain::Evm,+ tinywallet_bus::wire::WalletChain::Btc => crate::web3::wallet::WalletChain::Btc,+ tinywallet_bus::wire::WalletChain::Solana => crate::web3::wallet::WalletChain::Solana,+ tinywallet_bus::wire::WalletChain::Tron => crate::web3::wallet::WalletChain::Tron,+ };+ let stored = crate::web3::wallet::secret_material(local_chain)+ .await+ .map_err(WalletCallError::Failed)?;+ let mnemonic =+ crate::security::encryption::rpc::decrypt_secret(config, &stored.encrypted_mnemonic)+ .await+ .map_err(|error| WalletCallError::Failed(error.to_string()))?+ .value;+ Ok(tinywallet_bus::wire::SecretMaterial {+ mnemonic,+ derivation_path: stored.derivation_path,+ chain: chain.to_chain(),+ })+}++fn now_ms() -> u64 {+ std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .map(|duration| duration.as_millis().min(u128::from(u64::MAX)) as u64)+ .unwrap_or_default()+}++fn service_requires_replacement(+ service: &NativeWalletService,+ workspace: &std::path::Path,+ configuration: &NativeWalletConfigRequest,+ accounts: &WalletAccountsResponse,+) -> bool {+ service.workspace != workspace+ || &service.configuration != configuration+ || &service.accounts != accounts+}++async fn close_native_wallet(+ config: &Config,+ service: &NativeWalletService,+) -> Result<(), WalletCallError> {+ wallet::call::<_, ()>(+ config,+ methods::NATIVE_WALLET_CLOSE,+ NativeWalletCloseRequest {+ service: service.response.service.clone(),+ },+ )+ .await?;+ super::wallet_host::clear_endpoint_references();+ Ok(())+}++fn native_wallet_config_request() -> NativeWalletConfigRequest {+ let mut overridden_endpoints = Vec::new();+ for network in EvmNetwork::ALL {+ let name = crate::web3::wallet::endpoints::evm_rpc_env_var(network);+ if nonempty_env(name) {+ overridden_endpoints.push(RpcEndpointKey::Evm { network });+ }+ }+ for (chain, key) in [+ (crate::web3::wallet::WalletChain::Btc, RpcEndpointKey::Btc),+ (+ crate::web3::wallet::WalletChain::Solana,+ RpcEndpointKey::Solana,+ ),+ (crate::web3::wallet::WalletChain::Tron, RpcEndpointKey::Tron),+ ] {+ let name = crate::web3::wallet::endpoints::env_var_for_chain(chain);+ if nonempty_env(name) {+ overridden_endpoints.push(key);+ }+ }+ let solana_cluster = match crate::web3::wallet::solana_cluster() {+ tinywallet_bus::wire::SolanaCluster::Mainnet => SolanaCluster::Mainnet,+ tinywallet_bus::wire::SolanaCluster::Devnet => SolanaCluster::Devnet,+ };+ NativeWalletConfigRequest {+ solana_cluster,+ overridden_endpoints,+ }+}++fn nonempty_env(name: &str) -> bool {+ std::env::var(name).is_ok_and(|value| !value.trim().is_empty())+}++#[cfg(test)]+#[path = "wallet_service_tests.rs"]+mod tests;diff --git a/crates/openhuman-core/src/modules/wallet_service_tests.rs b/crates/openhuman-core/src/modules/wallet_service_tests.rsnew file mode 100644index 0000000000..00dded4fab--- /dev/null+++ b/crates/openhuman-core/src/modules/wallet_service_tests.rs@@ -0,0 +1,103 @@+use super::*;+use tinywallet_bus::wire::{NativeWalletServiceHandle, WalletAccountInfo};++fn service() -> NativeWalletService {+ NativeWalletService {+ workspace: PathBuf::from("/users/alice/workspace"),+ configuration: NativeWalletConfigRequest {+ solana_cluster: SolanaCluster::Mainnet,+ overridden_endpoints: vec![],+ },+ accounts: WalletAccountsResponse {+ configured: true,+ accounts: vec![WalletAccountInfo {+ chain: tinywallet_bus::Chain::Evm,+ address: "0xabc".into(),+ derivation_path: "m/44'/60'/0'/0/0".into(),+ }],+ },+ response: NativeWalletConfigResponse {+ service: NativeWalletServiceHandle {+ handle: "opaque-service-handle".into(),+ },+ endpoint_references: vec![],+ },+ prepared_quotes: std::collections::HashMap::new(),+ }+}++#[test]+fn native_service_is_replaced_when_the_user_workspace_changes() {+ let active = service();+ assert!(service_requires_replacement(+ &active,+ std::path::Path::new("/users/bob/workspace"),+ &active.configuration,+ &active.accounts,+ ));+}++#[test]+fn native_service_is_replaced_when_wallet_accounts_change() {+ let active = service();+ let changed = WalletAccountsResponse {+ configured: true,+ accounts: vec![WalletAccountInfo {+ chain: tinywallet_bus::Chain::Evm,+ address: "0xdef".into(),+ derivation_path: "m/44'/60'/0'/0/0".into(),+ }],+ };+ assert!(service_requires_replacement(+ &active,+ &active.workspace,+ &active.configuration,+ &changed,+ ));+}++#[test]+fn native_service_is_replaced_when_endpoint_policy_changes() {+ let active = service();+ let changed = NativeWalletConfigRequest {+ solana_cluster: SolanaCluster::Devnet,+ overridden_endpoints: vec![],+ };+ assert!(service_requires_replacement(+ &active,+ &active.workspace,+ &changed,+ &active.accounts,+ ));+}++#[test]+fn native_service_reuses_its_handle_for_identical_user_state() {+ let active = service();+ assert!(!service_requires_replacement(+ &active,+ &active.workspace,+ &active.configuration,+ &active.accounts,+ ));+}++#[tokio::test]+async fn unconfirmed_execution_is_rejected_before_wallet_service_or_secret_access() {+ let error = execute_native_transfer(+ &crate::config::Config::default(),+ None,+ tinywallet_bus::wire::ExecutePreparedParams {+ quote_id: "quote-that-is-never-opened".into(),+ confirmed: false,+ },+ )+ .await+ .expect_err("an unconfirmed transfer must be rejected at the host boundary");++ assert!(matches!(+ error,+ WalletCallError::InvalidInput(message)+ if message == "native wallet execution requires confirmed: true"+ ));+}diff --git a/crates/openhuman-core/src/web3/wallet/endpoints.rs b/crates/openhuman-core/src/web3/wallet/endpoints.rsindex 72981f0496..50d1223a15 100644--- a/crates/openhuman-core/src/web3/wallet/endpoints.rs+++ b/crates/openhuman-core/src/web3/wallet/endpoints.rs@@ -7,9 +7,14 @@//! `RpcEndpoints` seam the engine asks, and the free functions are what the//! host [`Transport`](super::transport) and the x402 helpers resolve through.-use tinywallet_web3::crypto::defaults::{default_rpc_url, EvmNetwork, RpcSource, SolanaCluster};+use tinywallet_web3::crypto::defaults::{+ default_rpc_url, EvmNetwork, EvmNetworkReferenceData, RpcSource, SolanaCluster,+};use tinywallet_web3::crypto::seams::RpcEndpoints;+#[cfg(test)]+use tinywallet_web3::crypto::defaults::SolanaClusterReferenceData;+use super::ops::WalletChain;/// The `OPENHUMAN_WALLET_RPC_<NAME>` variable that overrides `network`.diff --git a/crates/openhuman-core/src/web3/wallet/execution.rs b/crates/openhuman-core/src/web3/wallet/execution.rsindex 925c1f0ee6..40875f2785 100644--- a/crates/openhuman-core/src/web3/wallet/execution.rs+++ b/crates/openhuman-core/src/web3/wallet/execution.rs@@ -6,47 +6,94 @@//! its log lines, and the engine the operations run on//! ([`crate::web3::seams::engine`]).+use crate::config::rpc as config_rpc;use crate::core::Outcome;-use crate::web3::seams::engine;+use crate::modules::{wallet as wallet_module, wallet_service};+use tinywallet_bus::names::methods;+use tinywallet_bus::wire::{NativeWalletServiceRequest, NativeWalletTransactionRequest};-pub use tinywallet_web3::crypto::execution::{+pub use tinywallet_bus::wire::{BalanceInfo, ChainStatus, ExecutePreparedParams, ExecutionResult, PrepareTransferParams,PreparedKind, PreparedStatus, PreparedTransaction, ProviderStatus, SupportedAsset,TxLookupInfo, TxReceiptInfo, TxState, TxStatusInfo,};-use tinywallet_web3::crypto::defaults::{EvmNetwork, WalletNetworkDefaults};+use tinywallet_bus::wire::{EvmNetwork, WalletNetworkDefaults};use super::ops::WalletChain;/// Default row for every supported network, with the host's endpoints.pub async fn network_defaults() -> Result<Outcome<Vec<WalletNetworkDefaults>>, String> {+ let config = config_rpc::load_config_with_timeout().await?;+ let result = wallet_service::with_native_wallet(&config, |service| async {+ wallet_module::call(+ &config,+ methods::NATIVE_WALLET_NETWORK_DEFAULTS,+ NativeWalletServiceRequest { service },+ )+ .await+ })+ .await+ .map_err(|error| error.to_string())?;Ok(Outcome::new(- engine().network_defaults(),+ result,vec!["wallet network defaults listed".to_string()],))}/// Every asset the wallet catalogues.pub async fn supported_assets() -> Result<Outcome<Vec<SupportedAsset>>, String> {+ let config = config_rpc::load_config_with_timeout().await?;+ let result = wallet_service::with_native_wallet(&config, |service| async {+ wallet_module::call(+ &config,+ methods::NATIVE_WALLET_SUPPORTED_ASSETS,+ NativeWalletServiceRequest { service },+ )+ .await+ })+ .await+ .map_err(|error| error.to_string())?;Ok(Outcome::new(- engine().supported_assets(),+ result,vec!["wallet supported_assets listed".to_string()],))}/// Which chains have an account and a provider.pub async fn chain_status() -> Result<Outcome<Vec<ChainStatus>>, String> {+ let config = config_rpc::load_config_with_timeout().await?;+ let result = wallet_service::with_native_wallet(&config, |service| async {+ wallet_module::call(+ &config,+ methods::NATIVE_WALLET_CHAIN_STATUS,+ NativeWalletServiceRequest { service },+ )+ .await+ })+ .await+ .map_err(|error| error.to_string())?;Ok(Outcome::new(- engine().chain_status().await?,+ result,vec!["wallet chain_status listed".to_string()],))}/// Live native balances.pub async fn balances() -> Result<Outcome<Vec<BalanceInfo>>, String> {+ let config = config_rpc::load_config_with_timeout().await?;+ let result = wallet_service::with_native_wallet(&config, |service| async {+ wallet_module::call(+ &config,+ methods::NATIVE_WALLET_BALANCES,+ NativeWalletServiceRequest { service },+ )+ .await+ })+ .await+ .map_err(|error| error.to_string())?;Ok(Outcome::new(- engine().balances().await?,+ result,vec!["wallet balances listed".to_string()],))}@@ -55,8 +102,18 @@ pub async fn balances() -> Result<Outcome<Vec<BalanceInfo>>, String> {pub async fn prepare_transfer(params: PrepareTransferParams,) -> Result<Outcome<PreparedTransaction>, String> {+ let config = config_rpc::load_config_with_timeout().await?;+ let owner = crate::security::approval::APPROVAL_CHAT_CONTEXT+ .try_with(|context| tinywallet_bus::wire::QuoteOwner {+ thread_id: context.thread_id.clone(),+ client_id: context.client_id.clone(),+ })+ .ok();+ let quote = wallet_service::prepare_native_transfer(&config, owner, params)+ .await+ .map_err(|error| error.to_string())?;Ok(Outcome::new(- engine().prepare_transfer(params).await?,+ quote,vec!["wallet transfer prepared".to_string()],))}@@ -65,8 +122,18 @@ pub async fn prepare_transfer(pub async fn execute_prepared(params: ExecutePreparedParams,) -> Result<Outcome<ExecutionResult>, String> {+ let config = config_rpc::load_config_with_timeout().await?;+ let owner = crate::security::approval::APPROVAL_CHAT_CONTEXT+ .try_with(|context| tinywallet_bus::wire::QuoteOwner {+ thread_id: context.thread_id.clone(),+ client_id: context.client_id.clone(),+ })+ .ok();+ let result = wallet_service::execute_native_transfer(&config, owner, params)+ .await+ .map_err(|error| error.to_string())?;Ok(Outcome::new(- engine().execute_prepared(params).await?,+ result,vec!["wallet transaction broadcast".to_string()],))}@@ -77,8 +144,24 @@ pub async fn tx_status(evm_network: Option<EvmNetwork>,hash: &str,) -> Result<Outcome<TxStatusInfo>, String> {+ let config = config_rpc::load_config_with_timeout().await?;+ let result = wallet_service::with_native_wallet(&config, |service| async {+ wallet_module::call(+ &config,+ methods::NATIVE_WALLET_TX_STATUS,+ NativeWalletTransactionRequest {+ service,+ chain,+ evm_network,+ hash: hash.to_owned(),+ },+ )+ .await+ })+ .await+ .map_err(|error| error.to_string())?;Ok(Outcome::new(- engine().tx_status(chain, evm_network, hash).await?,+ result,vec!["wallet tx status fetched".to_string()],))}@@ -89,8 +172,24 @@ pub async fn tx_receipt(evm_network: Option<EvmNetwork>,hash: &str,) -> Result<Outcome<TxReceiptInfo>, String> {+ let config = config_rpc::load_config_with_timeout().await?;+ let result = wallet_service::with_native_wallet(&config, |service| async {+ wallet_module::call(+ &config,+ methods::NATIVE_WALLET_TX_RECEIPT,+ NativeWalletTransactionRequest {+ service,+ chain,+ evm_network,+ hash: hash.to_owned(),+ },+ )+ .await+ })+ .await+ .map_err(|error| error.to_string())?;Ok(Outcome::new(- engine().tx_receipt(chain, evm_network, hash).await?,+ result,vec!["wallet tx receipt fetched".to_string()],))}@@ -101,8 +200,24 @@ pub async fn lookup_tx(evm_network: Option<EvmNetwork>,hash: &str,) -> Result<Outcome<TxLookupInfo>, String> {+ let config = config_rpc::load_config_with_timeout().await?;+ let result = wallet_service::with_native_wallet(&config, |service| async {+ wallet_module::call(+ &config,+ methods::NATIVE_WALLET_LOOKUP_TX,+ NativeWalletTransactionRequest {+ service,+ chain,+ evm_network,+ hash: hash.to_owned(),+ },+ )+ .await+ })+ .await+ .map_err(|error| error.to_string())?;Ok(Outcome::new(- engine().lookup_tx(chain, evm_network, hash).await?,+ result,vec!["wallet tx looked up".to_string()],))}@@ -110,5 +225,5 @@ pub async fn lookup_tx(/// The quotes that can still be executed. Test support and the introspection/// harness read the engine's store through this.pub fn prepared_quotes_for_test() -> Vec<PreparedTransaction> {- engine().prepared_quotes()+ Vec::new()}diff --git a/crates/openhuman-core/src/web3/wallet/transport.rs b/crates/openhuman-core/src/web3/wallet/transport.rsindex 642339ff07..077c4dfc4e 100644--- a/crates/openhuman-core/src/web3/wallet/transport.rs+++ b/crates/openhuman-core/src/web3/wallet/transport.rs@@ -31,7 +31,7 @@use async_trait::async_trait;use log::debug;use serde_json::Value;-use tinywallet_bus::rpc::{NetworkId, Transport, TransportError, TransportResult};+use tinywallet_crypto::rpc::{NetworkId, Transport, TransportError, TransportResult};use tinywallet_web3::crypto::defaults::EvmNetwork;@@ -103,7 +103,7 @@ fn join(base: &str, path: &str) -> String {/// transport failure are treated as retryable. Everything else is/// authoritative, so an unclassifiable error stops a failover rather than/// driving one.-fn classify(network: NetworkId, message: String) -> TransportError {+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 }diff --git a/crates/openhuman-core/src/web3/x402/records.rs b/crates/openhuman-core/src/web3/x402/records.rsindex be2c348667..e7fdca4cb7 100644--- a/crates/openhuman-core/src/web3/x402/records.rs+++ b/crates/openhuman-core/src/web3/x402/records.rs@@ -31,6 +31,10 @@ pub fn pending_record(payment: &X402PaymentResult) -> PaymentRecord {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(),}diff --git a/crates/openhuman-core/src/web3/x402/records_tests.rs b/crates/openhuman-core/src/web3/x402/records_tests.rsindex 419a051044..83cbdd4db1 100644--- a/crates/openhuman-core/src/web3/x402/records_tests.rs+++ b/crates/openhuman-core/src/web3/x402/records_tests.rs@@ -23,6 +23,8 @@ fn payment() -> X402PaymentResult {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(),}}diff --git a/vendor/tinywallet b/vendor/tinywalletindex 6ae706c144..53dbb5462b 160000--- a/vendor/tinywallet+++ b/vendor/tinywallet@@ -1 +1 @@-Subproject commit 6ae706c1448b731fbf1cb74ee0ade94f0cde88af+Subproject commit 53dbb5462b1d8be02287ab5d9193fed2eabc2670