Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

fix(wallet): close native service on sign-out and shutdown

Steven Enamakelf7d85b1a57ee
diff --git a/crates/openhuman-core/src/modules/wallet_host.rs b/crates/openhuman-core/src/modules/wallet_host.rs
index b869a9ef7e..cf7d8958ef 100644
--- a/crates/openhuman-core/src/modules/wallet_host.rs
+++ b/crates/openhuman-core/src/modules/wallet_host.rs
@@ -96,6 +96,13 @@ pub(crate) fn clear_endpoint_references() {
}
}
+#[cfg(test)]
+pub(super) fn has_endpoint_reference_for_test(reference: &str) -> bool {
+ endpoint_references()
+ .lock()
+ .is_ok_and(|references| references.contains_key(reference))
+}
+
pub(crate) async fn wallet_accounts_snapshot(
) -> Result<tinywallet_bus::wire::WalletAccountsResponse, String> {
let status = crate::web3::wallet::status()
diff --git a/crates/openhuman-core/src/modules/wallet_service.rs b/crates/openhuman-core/src/modules/wallet_service.rs
index bed6c26af2..8794ffbc82 100644
--- a/crates/openhuman-core/src/modules/wallet_service.rs
+++ b/crates/openhuman-core/src/modules/wallet_service.rs
@@ -3,6 +3,7 @@
use std::collections::HashMap;
use std::future::Future;
use std::path::PathBuf;
+use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::OnceLock;
use tinywallet_bus::names::methods;
@@ -17,6 +18,7 @@ use crate::config::Config;
use super::wallet::{self, WalletCallError};
struct NativeWalletService {
+ config: Config,
workspace: PathBuf,
configuration: NativeWalletConfigRequest,
accounts: WalletAccountsResponse,
@@ -26,6 +28,7 @@ struct NativeWalletService {
static NATIVE_WALLET_SERVICE: OnceLock<tokio::sync::Mutex<Option<NativeWalletService>>> =
OnceLock::new();
+static NATIVE_WALLET_SHUTDOWN_HOOK_REGISTERED: AtomicBool = AtomicBool::new(false);
fn native_wallet_service() -> &'static tokio::sync::Mutex<Option<NativeWalletService>> {
NATIVE_WALLET_SERVICE.get_or_init(|| tokio::sync::Mutex::new(None))
@@ -44,6 +47,7 @@ where
R: Send,
{
let mut active = native_wallet_service().lock().await;
+ register_native_wallet_shutdown_hook();
let accounts = super::wallet_host::wallet_accounts_snapshot()
.await
.map_err(WalletCallError::Failed)?;
@@ -98,24 +102,27 @@ async fn ensure_native_wallet(
return Err(WalletCallError::Failed(error));
}
*active = Some(NativeWalletService {
+ config: config.clone(),
workspace,
configuration,
accounts,
response,
prepared_quotes: HashMap::new(),
});
+ register_native_wallet_shutdown_hook();
}
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.
+/// Prepare a native transfer through the module and retain its exact quote so
+/// the host can bind approval and signer selection to the same immutable facts.
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;
+ register_native_wallet_shutdown_hook();
let accounts = super::wallet_host::wallet_accounts_snapshot()
.await
.map_err(WalletCallError::Failed)?;
@@ -165,6 +172,7 @@ pub(crate) async fn execute_native_transfer(
}
let mut active = native_wallet_service().lock().await;
+ register_native_wallet_shutdown_hook();
let accounts = super::wallet_host::wallet_accounts_snapshot()
.await
.map_err(WalletCallError::Failed)?;
@@ -268,6 +276,65 @@ async fn close_native_wallet(
Ok(())
}
+/// Close the current per-user service on sign-out or process shutdown. The
+/// mutex waits for any in-flight bus call to finish before releasing quote and
+/// endpoint state, so a later user cannot inherit an old handle.
+pub(crate) async fn close_native_wallet_service() -> Result<(), WalletCallError> {
+ register_native_wallet_shutdown_hook();
+ close_native_wallet_service_inner().await
+}
+
+async fn close_native_wallet_service_inner() -> Result<(), WalletCallError> {
+ let mut active = native_wallet_service().lock().await;
+ let config = active.as_ref().map(|service| service.config.clone());
+ close_active_native_wallet_with(&mut active, move |request| async move {
+ let Some(config) = config else {
+ return Ok(());
+ };
+ wallet::call::<_, ()>(&config, methods::NATIVE_WALLET_CLOSE, request).await
+ })
+ .await
+}
+
+async fn close_active_native_wallet_with<F, Fut>(
+ active: &mut Option<NativeWalletService>,
+ close: F,
+) -> Result<(), WalletCallError>
+where
+ F: FnOnce(NativeWalletCloseRequest) -> Fut,
+ Fut: Future<Output = Result<(), WalletCallError>>,
+{
+ if let Some(service) = active.as_ref() {
+ close(NativeWalletCloseRequest {
+ service: service.response.service.clone(),
+ })
+ .await?;
+ }
+ *active = None;
+ super::wallet_host::clear_endpoint_references();
+ Ok(())
+}
+
+fn register_native_wallet_shutdown_hook() {
+ if !begin_shutdown_hook_registration(&NATIVE_WALLET_SHUTDOWN_HOOK_REGISTERED) {
+ return;
+ }
+ crate::core::shutdown::register(|| async {
+ finish_shutdown_hook_registration(&NATIVE_WALLET_SHUTDOWN_HOOK_REGISTERED);
+ if let Err(error) = close_native_wallet_service_inner().await {
+ tracing::warn!(%error, "[modules:wallet] failed to close native wallet service at shutdown");
+ }
+ });
+}
+
+fn begin_shutdown_hook_registration(registered: &AtomicBool) -> bool {
+ !registered.swap(true, Ordering::AcqRel)
+}
+
+fn finish_shutdown_hook_registration(registered: &AtomicBool) {
+ registered.store(false, Ordering::Release);
+}
+
fn native_wallet_config_request() -> NativeWalletConfigRequest {
let mut overridden_endpoints = Vec::new();
for network in EvmNetwork::ALL {
diff --git a/crates/openhuman-core/src/modules/wallet_service_tests.rs b/crates/openhuman-core/src/modules/wallet_service_tests.rs
index 00dded4fab..a02f790e36 100644
--- a/crates/openhuman-core/src/modules/wallet_service_tests.rs
+++ b/crates/openhuman-core/src/modules/wallet_service_tests.rs
@@ -1,8 +1,13 @@
use super::*;
+use std::sync::{
+ atomic::{AtomicBool, AtomicUsize, Ordering},
+ Arc,
+};
use tinywallet_bus::wire::{NativeWalletServiceHandle, WalletAccountInfo};
fn service() -> NativeWalletService {
NativeWalletService {
+ config: crate::config::Config::default(),
workspace: PathBuf::from("/users/alice/workspace"),
configuration: NativeWalletConfigRequest {
solana_cluster: SolanaCluster::Mainnet,
@@ -26,6 +31,107 @@ fn service() -> NativeWalletService {
}
}
+#[test]
+fn shutdown_hook_guard_allows_registration_after_hooks_are_drained() {
+ let registered = AtomicBool::new(false);
+ assert!(begin_shutdown_hook_registration(&registered));
+ assert!(!begin_shutdown_hook_registration(&registered));
+
+ finish_shutdown_hook_registration(&registered);
+
+ assert!(begin_shutdown_hook_registration(&registered));
+}
+
+#[tokio::test]
+async fn explicit_close_retains_state_for_retry_then_releases_user_state_once() {
+ let mut active = Some(service());
+ active
+ .as_mut()
+ .expect("fixture service")
+ .prepared_quotes
+ .insert(
+ "old-user-quote".into(),
+ tinywallet_bus::wire::PreparedTransaction {
+ quote_id: "old-user-quote".into(),
+ kind: tinywallet_bus::wire::PreparedKind::NativeTransfer,
+ chain: tinywallet_bus::wire::WalletChain::Evm,
+ evm_network: Some(EvmNetwork::EthereumMainnet),
+ from_address: "0xalice".into(),
+ to_address: "0xbob".into(),
+ asset_symbol: "ETH".into(),
+ amount_raw: "1".into(),
+ amount_formatted: "1".into(),
+ receive_symbol: None,
+ min_receive_raw: None,
+ calldata: None,
+ token_address: None,
+ estimated_fee_raw: "1".into(),
+ status: tinywallet_bus::wire::PreparedStatus::AwaitingConfirmation,
+ created_at_ms: 1,
+ expires_at_ms: u64::MAX,
+ notes: vec![],
+ },
+ );
+ let configured = tinywallet_bus::wire::NativeWalletConfigResponse {
+ service: NativeWalletServiceHandle {
+ handle: "old-user-service".into(),
+ },
+ endpoint_references: vec![tinywallet_bus::wire::HostEndpointReference {
+ key: tinywallet_bus::wire::RpcEndpointKey::Btc,
+ reference: "old-user-endpoint".into(),
+ }],
+ };
+ super::super::wallet_host::bind_endpoint_references(&configured)
+ .expect("fixture endpoint alias should bind");
+ let close_calls = Arc::new(AtomicUsize::new(0));
+ let observed_calls = close_calls.clone();
+
+ close_active_native_wallet_with(&mut active, move |request| async move {
+ assert_eq!(request.service.handle, "opaque-service-handle");
+ observed_calls.fetch_add(1, Ordering::SeqCst);
+ Err(WalletCallError::Failed("temporary close failure".into()))
+ })
+ .await
+ .expect_err("an unacknowledged close must remain retryable");
+
+ assert_eq!(close_calls.load(Ordering::SeqCst), 1);
+ assert!(
+ active
+ .as_ref()
+ .is_some_and(|service| service.prepared_quotes.contains_key("old-user-quote")),
+ "failed close must retain the service quote state"
+ );
+ assert!(
+ super::super::wallet_host::has_endpoint_reference_for_test("old-user-endpoint"),
+ "failed close must retain aliases needed for retry"
+ );
+
+ let observed_calls = close_calls.clone();
+ close_active_native_wallet_with(&mut active, move |request| async move {
+ assert_eq!(request.service.handle, "opaque-service-handle");
+ observed_calls.fetch_add(1, Ordering::SeqCst);
+ Ok(())
+ })
+ .await
+ .expect("successful retry should release the service");
+
+ assert_eq!(close_calls.load(Ordering::SeqCst), 2);
+ assert!(active.is_none(), "the cached quote set must be released");
+ assert!(
+ !super::super::wallet_host::has_endpoint_reference_for_test("old-user-endpoint"),
+ "endpoint aliases from the signed-out user must be removed"
+ );
+
+ let observed_calls = close_calls.clone();
+ close_active_native_wallet_with(&mut active, move |_request| async move {
+ observed_calls.fetch_add(1, Ordering::SeqCst);
+ Ok(())
+ })
+ .await
+ .expect("closing an already-empty service is a no-op");
+ assert_eq!(close_calls.load(Ordering::SeqCst), 2);
+}
+
#[test]
fn native_service_is_replaced_when_the_user_workspace_changes() {
let active = service();
diff --git a/crates/openhuman-core/src/security/credentials/ops/credential.rs b/crates/openhuman-core/src/security/credentials/ops/credential.rs
index 081644ae92..13fff43a22 100644
--- a/crates/openhuman-core/src/security/credentials/ops/credential.rs
+++ b/crates/openhuman-core/src/security/credentials/ops/credential.rs
@@ -504,6 +504,11 @@ pub async fn clear_credential(
async fn clear_session_credential(config: &Config) -> Result<Outcome<bool>, String> {
let mut logs = Vec::new();
crate::cron::scheduler_gate::set_signed_out(true);
+ #[cfg(feature = "web3")]
+ if let Err(error) = crate::modules::wallet_service::close_native_wallet_service().await {
+ tracing::warn!(%error, "{LOG_PREFIX} failed to close native wallet service during sign-out");
+ logs.push("native wallet service cleanup will retry on replacement or shutdown".into());
+ }
identity::clear_current_user();
// Local/CLI model authentication can outlive an OpenHuman account. The old
// account's listeners and workspace-bound channel state cannot.