Skip to content

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

feat(wallet): add mnemonic generation and recovery derivation

Steven Enamakel35a84fff69c8
diff --git a/crates/openhuman-core/src/modules/wallet.rs b/crates/openhuman-core/src/modules/wallet.rs
index 1e77eb33d9..20813ebedc 100644
--- a/crates/openhuman-core/src/modules/wallet.rs
+++ b/crates/openhuman-core/src/modules/wallet.rs
@@ -70,9 +70,12 @@ use serde::de::DeserializeOwned;
use serde::Serialize;
use tinywallet_bus::names::methods;
use tinywallet_bus::wire::{
- DerivedAccount, ExportRequest, ExportedKey, Scheme, SecretMaterial, SignMessageRequest,
- SignRequest, Signature, SignedTransaction, TransactionSpec,
+ DeriveMnemonicSeedRequest, DeriveMnemonicSeedResponse, DerivedAccount, ExportRequest,
+ ExportedKey, GenerateMnemonicRequest, GenerateMnemonicResponse, Scheme, SecretMaterial,
+ SignMessageRequest, SignRequest, Signature, SignedTransaction, TransactionSpec,
};
+use tinywallet_bus::Chain;
+use zeroize::Zeroize;
use super::{host, ops, registry};
use crate::config::Config;
@@ -147,15 +150,50 @@ pub async fn derive_account(
config: &Config,
secret: &SecretMaterial,
) -> Result<DerivedAccount, WalletCallError> {
- let proxy = attested_proxy(config).await?;
log::debug!(
"[modules:wallet] derive_account chain={:?} module={MODULE_ID} (confidential)",
secret.chain
);
- proxy
- .call_confidential(methods::DERIVE_ACCOUNT, (secret.clone(),))
- .await
- .map_err(|error| classify(&error))
+ let mut request = secret.clone();
+ let result = call_confidential(config, methods::DERIVE_ACCOUNT, &request).await;
+ request.mnemonic.zeroize();
+ result
+}
+
+/// Generate a recovery phrase inside the attested TinyWallet module.
+///
+/// # Errors
+///
+/// [`WalletCallError`]. The phrase is returned to the host for encryption and
+/// custody, but generation and BIP-39 vocabulary remain module-owned.
+pub async fn generate_mnemonic(
+ config: &Config,
+ word_count: u8,
+) -> Result<GenerateMnemonicResponse, WalletCallError> {
+ call_confidential(
+ config,
+ methods::GENERATE_MNEMONIC,
+ &GenerateMnemonicRequest { word_count },
+ )
+ .await
+}
+
+/// Derive a standard BIP-39 seed inside the attested module.
+///
+/// The caller uses the seed only for OpenHuman's generic storage-key KDF.
+///
+/// # Errors
+///
+/// [`WalletCallError`]. Invalid or unsupported phrases are classified as
+/// [`WalletCallError::InvalidInput`].
+pub async fn derive_mnemonic_seed(
+ config: &Config,
+ mnemonic: String,
+) -> Result<DeriveMnemonicSeedResponse, WalletCallError> {
+ let mut request = DeriveMnemonicSeedRequest { mnemonic };
+ let result = call_confidential(config, methods::DERIVE_MNEMONIC_SEED, &request).await;
+ request.mnemonic.zeroize();
+ result
}
/// Sign opaque bytes with the key derived from `secret`.
diff --git a/crates/openhuman-core/src/modules/wallet_tests.rs b/crates/openhuman-core/src/modules/wallet_tests.rs
index 026fb13913..8a69a54314 100644
--- a/crates/openhuman-core/src/modules/wallet_tests.rs
+++ b/crates/openhuman-core/src/modules/wallet_tests.rs
@@ -129,6 +129,19 @@ async fn a_disabled_host_reports_unavailable_without_starting_a_broker() {
super::ensure_ready(&config).await,
Err(WalletCallError::Unavailable(_))
));
+ assert!(matches!(
+ super::generate_mnemonic(&config, 12).await,
+ Err(WalletCallError::Unavailable(_))
+ ));
+ assert!(matches!(
+ super::derive_mnemonic_seed(
+ &config,
+ "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about"
+ .to_string(),
+ )
+ .await,
+ Err(WalletCallError::Unavailable(_))
+ ));
}
// ---------------------------------------------------------------------------
diff --git a/crates/openhuman-core/src/web3/wallet/mod.rs b/crates/openhuman-core/src/web3/wallet/mod.rs
index fc59a23cbc..36ce50285e 100644
--- a/crates/openhuman-core/src/web3/wallet/mod.rs
+++ b/crates/openhuman-core/src/web3/wallet/mod.rs
@@ -73,8 +73,11 @@ pub use execution::{
pub(crate) use ops::secret_material;
#[cfg(feature = "web3")]
pub use ops::{
- reveal_recovery_phrase, setup, status, RevealRecoveryPhraseResult, WalletAccount, WalletChain,
- WalletSetupParams, WalletSetupSource, WalletStatus, WALLET_NOT_CONFIGURED_MESSAGE,
+ derive_recovery_material, generate_recovery_phrase, reveal_recovery_phrase, setup, status,
+ validate_recovery_phrase, GeneratedRecoveryPhrase, RecoveryPhraseValidation,
+ RevealRecoveryPhraseResult, WalletAccount, WalletChain,
+ WalletRecoveryMaterial, WalletSetupParams, WalletSetupSource, WalletStatus,
+ WALLET_NOT_CONFIGURED_MESSAGE,
};
#[cfg(feature = "web3")]
pub use schemas::{
diff --git a/crates/openhuman-core/src/web3/wallet/ops.rs b/crates/openhuman-core/src/web3/wallet/ops.rs
index 18adadf11d..ba9780b4c2 100644
--- a/crates/openhuman-core/src/web3/wallet/ops.rs
+++ b/crates/openhuman-core/src/web3/wallet/ops.rs
@@ -18,14 +18,122 @@ use log::debug;
use crate::config::rpc as config_rpc;
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,
};
+use types::{GeneratedRecoveryPhrase, RecoveryPhraseValidation, WalletRecoveryMaterial};
const VALID_MNEMONIC_WORD_COUNTS: [u8; 5] = [12, 15, 18, 21, 24];
+/// Generate recovery material through the attested wallet module.
+pub async fn generate_recovery_phrase(
+ word_count: u8,
+) -> Result<Outcome<GeneratedRecoveryPhrase>, String> {
+ if !VALID_MNEMONIC_WORD_COUNTS.contains(&word_count) {
+ return Err(format!("unsupported mnemonic word count {word_count}"));
+ }
+ let config = config_rpc::load_config_with_timeout().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(
+ mnemonic: String,
+) -> Result<Outcome<WalletRecoveryMaterial>, String> {
+ let word_count = mnemonic.split_whitespace().count();
+ if !VALID_MNEMONIC_WORD_COUNTS.contains(&(word_count as u8)) {
+ return Err(format!(
+ "recovery phrase must contain one of {} words",
+ VALID_MNEMONIC_WORD_COUNTS
+ .iter()
+ .map(u8::to_string)
+ .collect::<Vec<_>>()
+ .join(", ")
+ ));
+ }
+
+ let config = config_rpc::load_config_with_timeout().await?;
+ 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(
+ mnemonic: String,
+) -> Result<Outcome<RecoveryPhraseValidation>, String> {
+ use crate::modules::wallet::WalletCallError;
+
+ let config = config_rpc::load_config_with_timeout().await?;
+ let valid = match crate::modules::wallet::derive_mnemonic_seed(&config, mnemonic).await {
+ Ok(mut response) => {
+ let valid = response.seed.len() == 64;
+ response.seed.zeroize();
+ valid
+ }
+ 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());
diff --git a/crates/openhuman-core/src/web3/wallet/ops/types.rs b/crates/openhuman-core/src/web3/wallet/ops/types.rs
index fc39daf778..1839b415d1 100644
--- a/crates/openhuman-core/src/web3/wallet/ops/types.rs
+++ b/crates/openhuman-core/src/web3/wallet/ops/types.rs
@@ -29,6 +29,41 @@ pub struct WalletSetupParams {
pub force: bool,
}
+/// Phrase generated or validated by TinyWallet and the derived accounts used
+/// by the local wallet setup flow.
+#[derive(Clone, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(rename_all = "camelCase")]
+pub struct WalletRecoveryMaterial {
+ /// Standard BIP-39 seed bytes. The frontend uses these only for the
+ /// existing OpenHuman storage-key KDF and clears its temporary buffer.
+ pub seed: Vec<u8>,
+ /// Public addresses and derivation paths for the four supported chains.
+ pub accounts: Vec<WalletAccount>,
+}
+
+impl std::fmt::Debug for WalletRecoveryMaterial {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.debug_struct("WalletRecoveryMaterial")
+ .field("seed", &"<redacted>")
+ .field("accounts", &self.accounts)
+ .finish()
+ }
+}
+
+/// Generated recovery phrase returned for encryption and user confirmation.
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(rename_all = "camelCase")]
+pub struct GeneratedRecoveryPhrase {
+ pub phrase: String,
+ pub word_count: u8,
+}
+
+/// Result of checking a recovery phrase with TinyWallet.
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
+pub struct RecoveryPhraseValidation {
+ pub valid: bool,
+}
+
/// Persisted on-disk (and/or keychain-backed) representation of wallet state.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
diff --git a/crates/openhuman-core/src/web3/wallet/schemas.rs b/crates/openhuman-core/src/web3/wallet/schemas.rs
index 223f2518b6..770a866b86 100644
--- a/crates/openhuman-core/src/web3/wallet/schemas.rs
+++ b/crates/openhuman-core/src/web3/wallet/schemas.rs
@@ -42,6 +42,17 @@ struct EncodeErc20TransferParams {
amount_raw: String,
}
+#[derive(Debug, Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct GenerateMnemonicParams {
+ word_count: u8,
+}
+
+#[derive(Debug, Deserialize)]
+struct RecoveryPhraseParams {
+ phrase: String,
+}
+
pub fn all_controller_schemas() -> Vec<ControllerSchema> {
all_wallet_controller_schemas()
}
@@ -69,6 +80,9 @@ pub fn all_wallet_controller_schemas() -> Vec<ControllerSchema> {
wallet_schemas("tx_receipt"),
wallet_schemas("lookup_tx"),
wallet_schemas("reveal_recovery_phrase"),
+ wallet_schemas("generate_mnemonic"),
+ wallet_schemas("validate_mnemonic"),
+ wallet_schemas("derive_recovery_material"),
]
}
@@ -126,6 +140,18 @@ pub fn all_wallet_registered_controllers() -> Vec<RegisteredController> {
schema: wallet_schemas("reveal_recovery_phrase"),
handler: handle_reveal_recovery_phrase,
},
+ RegisteredController {
+ schema: wallet_schemas("generate_mnemonic"),
+ handler: handle_generate_mnemonic,
+ },
+ RegisteredController {
+ schema: wallet_schemas("validate_mnemonic"),
+ handler: handle_validate_mnemonic,
+ },
+ RegisteredController {
+ schema: wallet_schemas("derive_recovery_material"),
+ handler: handle_derive_recovery_material,
+ },
]
}
@@ -349,6 +375,42 @@ pub fn wallet_schemas(function: &str) -> ControllerSchema {
required: true,
}],
},
+ "generate_mnemonic" => ControllerSchema {
+ namespace: "wallet",
+ function: "generate_mnemonic",
+ description: "Generate a recovery phrase inside the TinyWallet module.",
+ inputs: vec![required_json("wordCount", "BIP-39 word count: 12, 15, 18, 21, or 24.")],
+ outputs: vec![FieldSchema {
+ name: "result",
+ ty: TypeSchema::Json,
+ comment: "Generated recovery phrase and word count.",
+ required: true,
+ }],
+ },
+ "validate_mnemonic" => ControllerSchema {
+ namespace: "wallet",
+ function: "validate_mnemonic",
+ description: "Validate a recovery phrase in the TinyWallet module.",
+ inputs: vec![required_string("phrase", "Recovery phrase to validate.")],
+ outputs: vec![FieldSchema {
+ name: "result",
+ ty: TypeSchema::Json,
+ comment: "Whether the phrase is valid BIP-39 input.",
+ required: true,
+ }],
+ },
+ "derive_recovery_material" => ControllerSchema {
+ namespace: "wallet",
+ function: "derive_recovery_material",
+ description: "Derive the host storage-key seed and public wallet accounts through TinyWallet.",
+ inputs: vec![required_string("phrase", "Recovery phrase to derive wallet setup material from.")],
+ outputs: vec![FieldSchema {
+ name: "result",
+ ty: TypeSchema::Json,
+ comment: "Seed bytes for the OpenHuman storage-key KDF and derived public chain accounts.",
+ required: true,
+ }],
+ },
_ => ControllerSchema {
namespace: "wallet",
function: "unknown",
@@ -474,6 +536,36 @@ fn handle_reveal_recovery_phrase(_params: Map<String, Value>) -> ControllerFutur
})
}
+fn handle_generate_mnemonic(params: Map<String, Value>) -> ControllerFuture {
+ Box::pin(async move {
+ let parsed: GenerateMnemonicParams = serde_json::from_value(Value::Object(params))
+ .map_err(|e| format!("invalid params: {e}"))?;
+ crate::web3::wallet::generate_recovery_phrase(parsed.word_count)
+ .await?
+ .into_cli_compatible_json()
+ })
+}
+
+fn handle_validate_mnemonic(params: Map<String, Value>) -> ControllerFuture {
+ Box::pin(async move {
+ let parsed: RecoveryPhraseParams = serde_json::from_value(Value::Object(params))
+ .map_err(|e| format!("invalid params: {e}"))?;
+ crate::web3::wallet::validate_recovery_phrase(parsed.phrase)
+ .await?
+ .into_cli_compatible_json()
+ })
+}
+
+fn handle_derive_recovery_material(params: Map<String, Value>) -> ControllerFuture {
+ Box::pin(async move {
+ let parsed: RecoveryPhraseParams = serde_json::from_value(Value::Object(params))
+ .map_err(|e| format!("invalid params: {e}"))?;
+ crate::web3::wallet::derive_recovery_material(parsed.phrase)
+ .await?
+ .into_cli_compatible_json()
+ })
+}
+
/// Shared input schema for the tx_status / tx_receipt / lookup_tx readers.
fn tx_query_inputs() -> Vec<FieldSchema> {
vec![
@@ -498,6 +590,15 @@ fn required_json(name: &'static str, comment: &'static str) -> FieldSchema {
}
}
+fn required_string(name: &'static str, comment: &'static str) -> FieldSchema {
+ FieldSchema {
+ name,
+ ty: TypeSchema::String,
+ comment,
+ required: true,
+ }
+}
+
#[cfg(test)]
#[path = "schemas_tests.rs"]
mod tests;
diff --git a/crates/openhuman-core/src/web3/wallet/schemas_tests.rs b/crates/openhuman-core/src/web3/wallet/schemas_tests.rs
index 27fa015415..30fd3c8d66 100644
--- a/crates/openhuman-core/src/web3/wallet/schemas_tests.rs
+++ b/crates/openhuman-core/src/web3/wallet/schemas_tests.rs
@@ -2,19 +2,22 @@ use super::*;
#[test]
fn all_schemas_lists_every_controller() {
- assert_eq!(all_wallet_controller_schemas().len(), 15);
+ assert_eq!(all_wallet_controller_schemas().len(), 16);
}
#[test]
fn all_controllers_lists_every_handler() {
- assert_eq!(all_wallet_registered_controllers().len(), 15);
+ assert_eq!(all_wallet_registered_controllers().len(), 16);
}
#[test]
fn recovery_phrase_controllers_are_registered_with_the_expected_inputs() {
let generate = wallet_schemas("generate_mnemonic");
assert_eq!(generate.namespace, "wallet");
- assert!(generate.inputs.is_empty());
+ assert_eq!(
+ generate.inputs.iter().map(|field| field.name).collect::<Vec<_>>(),
+ vec!["wordCount"]
+ );
let validate = wallet_schemas("validate_mnemonic");
assert_eq!(validate.namespace, "wallet");
@@ -23,6 +26,12 @@ fn recovery_phrase_controllers_are_registered_with_the_expected_inputs() {
vec!["phrase"]
);
assert!(validate.inputs[0].required);
+
+ let derive = wallet_schemas("derive_recovery_material");
+ assert_eq!(
+ derive.inputs.iter().map(|field| field.name).collect::<Vec<_>>(),
+ vec!["phrase"]
+ );
}
#[test]