Skip to content

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

14.8 KB
Raw Blame
//! Wallet setup, status, and secret-material business operations.
//!
//! [`types`] holds the serde domain types shared across this module,
//! [`state`] owns the on-disk / keychain persistence for setup state, and
//! this file exposes the actual RPC-facing operations.

mod state;
mod types;

use crate::core::runtime::DispatchCtx;
use types::StoredWalletState;
pub(crate) use types::{inspect_stored_wallet_state, WalletSecretMaterial};
pub use types::{
    GeneratedRecoveryPhrase, RecoveryPhraseValidation, RevealRecoveryPhraseResult, WalletAccount,
    WalletChain, WalletRecoveryMaterial, WalletSetupParams, WalletSetupSource, WalletStatus,
    WALLET_NOT_CONFIGURED_MESSAGE,
};

use log::debug;

use crate::core::Outcome;
use tinywallet_bus::wire::SecretMaterial;
use tinywallet_bus::Chain as ModuleChain;
use zeroize::{Zeroize, Zeroizing};

use state::{
    keychain_load_mnemonic, load_stored_wallet_state_unlocked, save_stored_wallet_state_unlocked,
    to_status, LOG_PREFIX, WALLET_STATE_FILE_LOCK,
};

fn supported_word_counts() -> String {
    tinywallet_bus::MNEMONIC_WORD_COUNTS
        .iter()
        .map(u8::to_string)
        .collect::<Vec<_>>()
        .join(", ")
}

/// Generate recovery material through the attested wallet module.
pub async fn generate_recovery_phrase(
    ctx: &DispatchCtx,
    word_count: u8,
) -> Result<Outcome<GeneratedRecoveryPhrase>, String> {
    tinywallet_bus::validate_mnemonic_word_count(word_count).map_err(|error| error.to_string())?;
    let config = ctx.load_config().await?;
    let generated = crate::modules::wallet::generate_mnemonic(&config, word_count)
        .await
        .map_err(|error| error.to_string())?;
    Ok(Outcome::new(
        GeneratedRecoveryPhrase {
            phrase: generated.phrase,
            word_count: generated.word_count,
        },
        vec!["recovery phrase generated by wallet module".to_string()],
    ))
}

/// Validate a phrase and derive the public setup facts inside TinyWallet.
///
/// The returned BIP-39 seed is used only for OpenHuman's existing generic
/// storage-key KDF; mnemonic parsing and all chain derivation remain in the
/// confidential module operation.
pub async fn derive_recovery_material(
    ctx: &DispatchCtx,
    mnemonic: String,
) -> Result<Outcome<WalletRecoveryMaterial>, String> {
    let word_count = mnemonic.split_whitespace().count();
    if tinywallet_bus::validate_mnemonic_word_count_usize(word_count).is_err() {
        return Err(format!(
            "recovery phrase must contain one of {} words",
            supported_word_counts()
        ));
    }

    let config = ctx.load_config().await?;
    let mnemonic = Zeroizing::new(mnemonic);
    let mnemonic = Zeroizing::new(mnemonic.split_whitespace().collect::<Vec<_>>().join(" "));
    let seed = crate::modules::wallet::derive_mnemonic_seed(&config, mnemonic.to_string())
        .await
        .map_err(|error| error.to_string())?;
    let seed = Zeroizing::new(seed.seed);
    if seed.len() != 64 {
        return Err("wallet module returned an invalid BIP-39 seed length".to_string());
    }

    let accounts = [
        (WalletChain::Evm, ModuleChain::Evm, "m/44'/60'/0'/0/0"),
        (WalletChain::Btc, ModuleChain::Btc, "m/44'/0'/0'/0/0"),
        (WalletChain::Solana, ModuleChain::Solana, "m/44'/501'/0'/0'"),
        (WalletChain::Tron, ModuleChain::Tron, "m/44'/195'/0'/0/0"),
    ];
    let mut derived_accounts = Vec::with_capacity(accounts.len());
    for (chain, module_chain, derivation_path) in accounts {
        let mut secret = SecretMaterial {
            mnemonic: mnemonic.to_string(),
            derivation_path: derivation_path.to_string(),
            chain: module_chain,
        };
        let derived = crate::modules::wallet::derive_account(&config, &secret).await;
        secret.mnemonic.zeroize();
        let derived = derived.map_err(|error| error.to_string())?;
        derived_accounts.push(WalletAccount {
            chain,
            address: derived.address,
            derivation_path: derivation_path.to_string(),
        });
    }

    Ok(Outcome::new(
        WalletRecoveryMaterial {
            seed: seed.to_vec(),
            accounts: derived_accounts,
        },
        vec!["recovery phrase validated and wallet accounts derived".to_string()],
    ))
}

/// Check whether a phrase is valid BIP-39 input without deriving account data.
pub async fn validate_recovery_phrase(
    ctx: &DispatchCtx,
    mnemonic: String,
) -> Result<Outcome<RecoveryPhraseValidation>, String> {
    use crate::modules::wallet::WalletCallError;

    let config = ctx.load_config().await?;
    let valid = match crate::modules::wallet::derive_mnemonic_seed(&config, mnemonic).await {
        Ok(mut response) => {
            if response.seed.len() != 64 {
                response.seed.zeroize();
                return Err("wallet module returned an invalid BIP-39 seed length".to_string());
            }
            response.seed.zeroize();
            true
        }
        Err(WalletCallError::InvalidInput(_)) => false,
        Err(error) => return Err(error.to_string()),
    };
    Ok(Outcome::new(
        RecoveryPhraseValidation { valid },
        vec!["recovery phrase checked by wallet module".to_string()],
    ))
}

fn validate_setup(params: &WalletSetupParams) -> Result<Vec<WalletAccount>, String> {
    if !params.consent_granted {
        return Err("wallet setup requires explicit consent".to_string());
    }
    if tinywallet_bus::validate_mnemonic_word_count(params.mnemonic_word_count).is_err() {
        return Err(format!(
            "unsupported mnemonic word count {}; expected one of {}",
            params.mnemonic_word_count,
            supported_word_counts()
        ));
    }
    if params
        .encrypted_mnemonic
        .as_ref()
        .map(|value| value.trim().is_empty())
        .unwrap_or(true)
    {
        return Err(
            "wallet setup requires encrypted mnemonic material for signing-enabled local wallets"
                .to_string(),
        );
    }

    let mut normalized = Vec::with_capacity(params.accounts.len());
    for account in &params.accounts {
        let address = account.address.trim();
        let derivation_path = account.derivation_path.trim();
        if address.is_empty() {
            return Err(format!(
                "wallet setup account '{}' is missing an address",
                account.chain.as_str()
            ));
        }
        if derivation_path.is_empty() {
            return Err(format!(
                "wallet setup account '{}' is missing a derivation path",
                account.chain.as_str()
            ));
        }
        normalized.push(WalletAccount {
            chain: account.chain,
            address: address.to_string(),
            derivation_path: derivation_path.to_string(),
        });
    }

    for chain in WalletChain::ALL {
        let count = normalized
            .iter()
            .filter(|account| account.chain == chain)
            .count();
        if count != 1 {
            return Err(format!(
                "wallet setup must include exactly one '{}' account",
                chain.as_str()
            ));
        }
    }

    Ok(normalized)
}

pub async fn status(ctx: &DispatchCtx) -> Result<Outcome<WalletStatus>, String> {
    let config = ctx.load_config().await?;
    let _guard = WALLET_STATE_FILE_LOCK.lock();
    let status = to_status(&config, load_stored_wallet_state_unlocked(&config)?);

    debug!(
        "{LOG_PREFIX} status configured={} onboarding_completed={} account_count={}",
        status.configured,
        status.onboarding_completed,
        status.accounts.len()
    );

    Ok(Outcome::new(
        status,
        vec!["wallet status fetched".to_string()],
    ))
}

pub async fn setup(
    ctx: &DispatchCtx,
    params: WalletSetupParams,
) -> Result<Outcome<WalletStatus>, String> {
    let config = ctx.load_config().await?;
    let accounts = validate_setup(&params)?;
    let encrypted_mnemonic = params
        .encrypted_mnemonic
        .as_ref()
        .map(|value| value.trim().to_string())
        .filter(|value| !value.is_empty())
        .ok_or_else(|| {
            "wallet setup requires encrypted mnemonic material for signing-enabled local wallets"
                .to_string()
        })?;

    // ── Idempotency guard: reject overwrite unless caller explicitly set force=true ──
    // Acquire lock before the existence check so no TOCTOU race is possible.
    let _guard = WALLET_STATE_FILE_LOCK.lock();
    if let Some(_existing) = load_stored_wallet_state_unlocked(&config)? {
        if !params.force {
            debug!("{LOG_PREFIX} setup rejected: wallet already configured and force=false");
            return Err("wallet is already configured; pass force=true to overwrite".to_string());
        }
        debug!("{LOG_PREFIX} setup: overwriting existing wallet (force=true)");
    }

    let state = StoredWalletState {
        consent_granted: params.consent_granted,
        source: params.source,
        mnemonic_word_count: params.mnemonic_word_count,
        encrypted_mnemonic: Some(encrypted_mnemonic),
        accounts,
        updated_at_ms: state::current_time_ms(),
    };

    save_stored_wallet_state_unlocked(&config, &state)?;
    let status = to_status(&config, Some(state));

    debug!(
        "{LOG_PREFIX} setup saved source={:?} account_count={} mnemonic_words={} secret_stored={}",
        status.source,
        status.accounts.len(),
        status.mnemonic_word_count.unwrap_or_default(),
        status.secret_stored
    );

    Ok(Outcome::new(status, vec!["wallet setup saved".to_string()]))
}

/// Decrypt and return the stored recovery phrase for the current wallet.
///
/// This is a read-only operation — it never writes to disk or the keychain.
/// The plaintext phrase is returned only in the RPC response and must be kept
/// in transient React state on the frontend; it must never be logged or persisted.
pub async fn reveal_recovery_phrase(
    ctx: &DispatchCtx,
) -> Result<Outcome<RevealRecoveryPhraseResult>, String> {
    debug!("{LOG_PREFIX} reveal_recovery_phrase ENTRY");

    let config = ctx.load_config().await.map_err(|e| {
        log::warn!("{LOG_PREFIX} reveal_recovery_phrase config load failed: {e}");
        e
    })?;

    // Acquire the lock to load state, then drop it before any await point.
    // parking_lot::MutexGuard is not Send, so it must not be held across awaits.
    let ciphertext = {
        let _guard = WALLET_STATE_FILE_LOCK.lock();
        debug!("{LOG_PREFIX} reveal_recovery_phrase state lock acquired");

        let state = match load_stored_wallet_state_unlocked(&config)? {
            Some(s) => s,
            None => {
                debug!("{LOG_PREFIX} reveal_recovery_phrase no wallet state found");
                return Err(
                    "No recovery phrase is available to reveal. Set up or unlock your wallet first."
                        .to_string(),
                );
            }
        };

        // Primary path: mnemonic is in the state returned by load (either from
        // the JSON field or merged in from the OS keychain by
        // load_stored_wallet_state_unlocked).  Fallback: probe the keychain
        // directly in case the mnemonic is stored there but was not merged into
        // `state` (e.g. headless / CI keychain that was transiently unavailable
        // during the initial probe inside load_stored_wallet_state_unlocked, or
        // any environment where the mnemonic lives only in the keychain).
        let enc_mnemonic_opt = state
            .encrypted_mnemonic
            .as_ref()
            .map(|v| v.trim().to_string())
            .filter(|v| !v.is_empty())
            .or_else(|| {
                debug!(
                    "{LOG_PREFIX} reveal_recovery_phrase: mnemonic absent from state, \
                     falling back to direct keychain probe"
                );
                keychain_load_mnemonic(&config)
                    .map(|v| v.trim().to_string())
                    .filter(|v| !v.is_empty())
            });

        enc_mnemonic_opt.ok_or_else(|| {
            debug!("{LOG_PREFIX} reveal_recovery_phrase encrypted mnemonic missing from state");
            "No recovery phrase is available to reveal. Set up or unlock your wallet first."
                .to_string()
        })?
        // _guard dropped here — before the decrypt await below
    };

    debug!("{LOG_PREFIX} reveal_recovery_phrase decrypting mnemonic");

    let phrase = crate::security::credentials::ops::decrypt_secret(&config, &ciphertext)
        .await
        .map_err(|e| {
            log::warn!("{LOG_PREFIX} reveal_recovery_phrase decrypt failed: {e}");
            format!("Failed to decrypt recovery phrase: {e}")
        })?
        .value;

    let word_count = phrase.split_whitespace().count();

    debug!(
        "{LOG_PREFIX} reveal_recovery_phrase OK word_count={}",
        word_count
    );

    Ok(Outcome::new(
        RevealRecoveryPhraseResult { phrase, word_count },
        vec!["recovery phrase revealed".to_string()],
    ))
}

pub(crate) async fn secret_material(
    ctx: &DispatchCtx,
    chain: WalletChain,
) -> Result<WalletSecretMaterial, String> {
    debug!(
        "{LOG_PREFIX} secret_material loading config chain={}",
        chain.as_str()
    );
    let config = ctx.load_config().await?;
    debug!(
        "{LOG_PREFIX} secret_material acquiring state lock chain={}",
        chain.as_str()
    );
    let _guard = WALLET_STATE_FILE_LOCK.lock();
    let state = match load_stored_wallet_state_unlocked(&config)? {
        Some(state) => state,
        None => {
            debug!(
                "{LOG_PREFIX} secret_material missing wallet state chain={}",
                chain.as_str()
            );
            return Err(WALLET_NOT_CONFIGURED_MESSAGE.to_string());
        }
    };
    let encrypted_mnemonic = state
        .encrypted_mnemonic
        .as_ref()
        .map(|value| value.trim().to_string())
        .filter(|value| !value.is_empty())
        .ok_or_else(|| {
            debug!(
                "{LOG_PREFIX} secret_material missing encrypted mnemonic chain={}",
                chain.as_str()
            );
            "wallet secret material is missing; re-import the recovery phrase to enable signing"
                .to_string()
        })?;
    let derivation_path = state
        .accounts
        .iter()
        .find(|account| account.chain == chain)
        .map(|account| account.derivation_path.clone())
        .ok_or_else(|| {
            debug!(
                "{LOG_PREFIX} secret_material missing account chain={}",
                chain.as_str()
            );
            format!("no wallet account derived for chain '{}'", chain.as_str())
        })?;
    debug!(
        "{LOG_PREFIX} secret_material loaded chain={} derivation_path={}",
        chain.as_str(),
        derivation_path
    );
    Ok(WalletSecretMaterial {
        encrypted_mnemonic,
        derivation_path,
    })
}

#[cfg(test)]
#[path = "ops_tests.rs"]
mod tests;