From a68e4cf41d1227f2f61d36f16f4986c784cc62b0 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Sun, 15 Nov 2026 21:44:59 +0000 Subject: [PATCH 01/32] feat(wallet): add secondary account index and label to wallet types WalletAccount now carries an index and optional label so secondary accounts derived from the same recovery phrase can be represented, with index 0 defaulting for state written before this change. WalletStatus exposes these as additional_accounts to keep the existing one-account-per-chain accounts list unchanged. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../src/web3/wallet/ops/types.rs | 36 ++++++++++++++++++- 1 file changed, 35 insertions(+), 1 deletion(-) diff --git a/crates/openhuman-core/src/web3/wallet/ops/types.rs b/crates/openhuman-core/src/web3/wallet/ops/types.rs index 623463a889c..321063f2457 100644 --- a/crates/openhuman-core/src/web3/wallet/ops/types.rs +++ b/crates/openhuman-core/src/web3/wallet/ops/types.rs @@ -17,12 +17,39 @@ pub enum WalletSetupSource { } /// A public account retained in OpenHuman's wallet setup state. +/// +/// Every chain has one primary account at `index` 0, which is the only +/// account the TinyWallet module's transfers, swaps and x402 payments use. +/// A chain may also have secondary accounts from the same recovery phrase +/// (`index` 1 and up, see [`super::SECONDARY_ACCOUNTS`]); they sign only +/// through `wallet.execute_prepared_program`, under their own +/// `[wallet_policy.accounts._]` section. #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] #[serde(rename_all = "camelCase")] pub struct WalletAccount { pub chain: WalletChain, pub address: String, pub derivation_path: String, + /// Account index on the chain. Absent in state written before secondary + /// accounts existed, which reads as the primary account. + #[serde(default, skip_serializing_if = "is_primary_index")] + pub index: u32, + /// Optional human label for a secondary account (`giveaway`). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub label: Option, +} + +#[allow(clippy::trivially_copy_pass_by_ref)] +fn is_primary_index(index: &u32) -> bool { + *index == 0 +} + +impl WalletAccount { + /// Whether this is the chain's primary (index 0) account. + #[must_use] + pub fn is_primary(&self) -> bool { + self.index == 0 + } } /// Host-owned wallet setup status exposed by the existing RPC surface. @@ -38,7 +65,12 @@ pub struct WalletStatus { pub source: Option, #[serde(skip_serializing_if = "Option::is_none")] pub mnemonic_word_count: Option, + /// The primary (index 0) account of each chain. pub accounts: Vec, + /// Secondary accounts (index 1 and up). Kept out of `accounts` so callers + /// that expect one account per chain are unaffected. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub additional_accounts: Vec, #[serde(skip_serializing_if = "Option::is_none")] pub updated_at_ms: Option, } @@ -67,7 +99,9 @@ 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, - /// Public addresses and derivation paths for the four supported chains. + /// Public addresses and derivation paths for the four supported chains' + /// primary accounts, followed by the secondary accounts + /// ([`super::SECONDARY_ACCOUNTS`]). pub accounts: Vec, } From e7a4bbd0046862da0010101f0de085dc525344fd Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Sun, 15 Nov 2026 21:45:06 +0000 Subject: [PATCH 02/32] feat(wallet): split primary and additional accounts in wallet status Wallet status now partitions stored accounts into primary and additional lists so callers can distinguish the main account from derived ones, and onboarding completion is based only on the presence of a primary account. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- crates/openhuman-core/src/web3/wallet/ops/state.rs | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/crates/openhuman-core/src/web3/wallet/ops/state.rs b/crates/openhuman-core/src/web3/wallet/ops/state.rs index aa402e7e202..df8b1be8165 100644 --- a/crates/openhuman-core/src/web3/wallet/ops/state.rs +++ b/crates/openhuman-core/src/web3/wallet/ops/state.rs @@ -396,14 +396,19 @@ pub(super) fn to_status(config: &Config, state: Option) -> su .map(|v| !v.trim().is_empty()) .unwrap_or(false); let secret_stored = secret_in_json || keychain_has_mnemonic(config); + let (accounts, additional_accounts) = state + .accounts + .into_iter() + .partition(super::WalletAccount::is_primary); super::WalletStatus { configured: true, - onboarding_completed: state.consent_granted && !state.accounts.is_empty(), + onboarding_completed: state.consent_granted && !accounts.is_empty(), consent_granted: state.consent_granted, secret_stored, source: Some(state.source), mnemonic_word_count: Some(state.mnemonic_word_count), - accounts: state.accounts, + accounts, + additional_accounts, updated_at_ms: Some(state.updated_at_ms), } } @@ -415,6 +420,7 @@ pub(super) fn to_status(config: &Config, state: Option) -> su source: None, mnemonic_word_count: None, accounts: Vec::new(), + additional_accounts: Vec::new(), updated_at_ms: None, }, } From 4a1b65964dd4d24d4cec61cbb9fbd2b9ad797d15 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Sun, 15 Nov 2026 21:45:12 +0000 Subject: [PATCH 03/32] fix(web3): annotate partition result types in wallet status Added explicit type annotations to the accounts partition result so the compiler can infer the collection types correctly. This resolves a type inference failure in the wallet status conversion. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- crates/openhuman-core/src/web3/wallet/ops/state.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/openhuman-core/src/web3/wallet/ops/state.rs b/crates/openhuman-core/src/web3/wallet/ops/state.rs index df8b1be8165..8d8e81e5abd 100644 --- a/crates/openhuman-core/src/web3/wallet/ops/state.rs +++ b/crates/openhuman-core/src/web3/wallet/ops/state.rs @@ -396,7 +396,7 @@ pub(super) fn to_status(config: &Config, state: Option) -> su .map(|v| !v.trim().is_empty()) .unwrap_or(false); let secret_stored = secret_in_json || keychain_has_mnemonic(config); - let (accounts, additional_accounts) = state + let (accounts, additional_accounts): (Vec<_>, Vec<_>) = state .accounts .into_iter() .partition(super::WalletAccount::is_primary); From 9f7db833e59a4403cddc173d00cb6c502abe1324 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Sun, 15 Nov 2026 21:45:51 +0000 Subject: [PATCH 04/32] feat(wallet): derive secondary accounts alongside primary ones Recovery and import now derive every account the host knows about, including a labelled secondary Solana account, instead of only the four primary chain accounts. Derivation paths and account metadata are centralised in a shared plan so new accounts can be added in one place. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- crates/openhuman-core/src/web3/wallet/ops.rs | 266 +++++++++++++++++-- 1 file changed, 240 insertions(+), 26 deletions(-) diff --git a/crates/openhuman-core/src/web3/wallet/ops.rs b/crates/openhuman-core/src/web3/wallet/ops.rs index 4541a4fe29f..398f809c3b8 100644 --- a/crates/openhuman-core/src/web3/wallet/ops.rs +++ b/crates/openhuman-core/src/web3/wallet/ops.rs @@ -28,6 +28,57 @@ use state::{ to_status, LOG_PREFIX, WALLET_STATE_FILE_LOCK, }; +/// The primary (index 0) account of each chain and its derivation path. +pub(crate) const PRIMARY_ACCOUNTS: [(WalletChain, &str); 4] = [ + (WalletChain::Evm, "m/44'/60'/0'/0/0"), + (WalletChain::Btc, "m/44'/0'/0'/0/0"), + (WalletChain::Solana, "m/44'/501'/0'/0'"), + (WalletChain::Tron, "m/44'/195'/0'/0/0"), +]; + +/// A secondary account derived from the same recovery phrase as the primary +/// accounts. It never signs module transfers; it signs only host-built +/// transactions through `wallet.execute_prepared_program`, under its own +/// `[wallet_policy.accounts._]` section. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) struct SecondaryAccount { + pub chain: WalletChain, + pub index: u32, + pub derivation_path: &'static str, + pub label: &'static str, +} + +/// Every secondary account the host knows how to derive. Recovery and import +/// derive them all; a wallet set up before an entry existed derives it on +/// first use ([`ensure_account`]). +/// +/// Solana index 1 follows the account-index convention Phantom and +/// `solana-keygen` use (`m/44'/501'/'/0'`). +pub(crate) const SECONDARY_ACCOUNTS: [SecondaryAccount; 1] = [SecondaryAccount { + chain: WalletChain::Solana, + index: 1, + derivation_path: "m/44'/501'/1'/0'", + label: "giveaway", +}]; + +/// The canonical derivation path of `chain`'s account `index`, if the host +/// knows that account. +pub(crate) fn account_derivation_path(chain: WalletChain, index: u32) -> Option<&'static str> { + if index == 0 { + return PRIMARY_ACCOUNTS + .iter() + .find(|(candidate, _)| *candidate == chain) + .map(|(_, path)| *path); + } + secondary_account(chain, index).map(|account| account.derivation_path) +} + +fn secondary_account(chain: WalletChain, index: u32) -> Option<&'static SecondaryAccount> { + SECONDARY_ACCOUNTS + .iter() + .find(|account| account.chain == chain && account.index == index) +} + fn supported_word_counts() -> String { tinywallet_bus::MNEMONIC_WORD_COUNTS .iter() @@ -83,27 +134,12 @@ pub async fn derive_recovery_material( 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(), - }); + let plan = derivation_plan(); + let mut derived_accounts = Vec::with_capacity(plan.len()); + for planned in plan { + let address = + derive_address(&config, &mnemonic, planned.chain, &planned.derivation_path).await?; + derived_accounts.push(WalletAccount { address, ..planned }); } Ok(Outcome::new( @@ -115,6 +151,53 @@ pub async fn derive_recovery_material( )) } +/// Every account recovery and import derive, address left blank: the primary +/// account of each chain in [`PRIMARY_ACCOUNTS`] order, then +/// [`SECONDARY_ACCOUNTS`]. +pub(crate) fn derivation_plan() -> Vec { + let primary = PRIMARY_ACCOUNTS.iter().map(|(chain, path)| WalletAccount { + chain: *chain, + address: String::new(), + derivation_path: (*path).to_string(), + index: 0, + label: None, + }); + let secondary = SECONDARY_ACCOUNTS.iter().map(|account| WalletAccount { + chain: account.chain, + address: String::new(), + derivation_path: account.derivation_path.to_string(), + index: account.index, + label: Some(account.label.to_string()), + }); + primary.chain(secondary).collect() +} + +fn module_chain(chain: WalletChain) -> ModuleChain { + match chain { + WalletChain::Evm => ModuleChain::Evm, + WalletChain::Btc => ModuleChain::Btc, + WalletChain::Solana => ModuleChain::Solana, + WalletChain::Tron => ModuleChain::Tron, + } +} + +/// Ask the module for the address at `derivation_path`. +async fn derive_address( + config: &crate::config::Config, + mnemonic: &str, + chain: WalletChain, + derivation_path: &str, +) -> Result { + let mut secret = SecretMaterial { + mnemonic: mnemonic.to_string(), + derivation_path: derivation_path.to_string(), + chain: module_chain(chain), + }; + let derived = crate::modules::wallet::derive_account(config, &secret).await; + secret.mnemonic.zeroize(); + Ok(derived.map_err(|error| error.to_string())?.address) +} + /// Check whether a phrase is valid BIP-39 input without deriving account data. pub async fn validate_recovery_phrase( ctx: &DispatchCtx, @@ -180,17 +263,44 @@ fn validate_setup(params: &WalletSetupParams) -> Result, Stri account.chain.as_str() )); } + if account.index > 0 { + // A secondary account must be one the host knows, at its canonical + // path, so the key it later signs with is the one its policy names. + let expected = account_derivation_path(account.chain, account.index); + if expected != Some(derivation_path) { + return Err(format!( + "wallet setup account '{}' index {} is not a known secondary account", + account.chain.as_str(), + account.index + )); + } + if normalized.iter().any(|existing: &WalletAccount| { + existing.chain == account.chain && existing.index == account.index + }) { + return Err(format!( + "wallet setup lists '{}' index {} more than once", + account.chain.as_str(), + account.index + )); + } + } normalized.push(WalletAccount { chain: account.chain, address: address.to_string(), derivation_path: derivation_path.to_string(), + index: account.index, + label: account + .label + .as_ref() + .map(|label| label.trim().to_string()) + .filter(|label| !label.is_empty()), }); } for chain in WalletChain::ALL { let count = normalized .iter() - .filter(|account| account.chain == chain) + .filter(|account| account.chain == chain && account.is_primary()) .count(); if count != 1 { return Err(format!( @@ -356,9 +466,15 @@ pub async fn reveal_recovery_phrase( )) } +/// The encrypted phrase and the derivation path of `chain`'s account `index`. +/// +/// A secondary account missing from state written before it existed resolves +/// to its canonical path ([`SECONDARY_ACCOUNTS`]), so signing never needs the +/// address to have been stored first. pub(crate) async fn secret_material( ctx: &DispatchCtx, chain: WalletChain, + index: u32, ) -> Result { debug!( "{LOG_PREFIX} secret_material loading config chain={}", @@ -396,17 +512,30 @@ pub(crate) async fn secret_material( let derivation_path = state .accounts .iter() - .find(|account| account.chain == chain) + .find(|account| account.chain == chain && account.index == index) .map(|account| account.derivation_path.clone()) + .or_else(|| { + (index > 0) + .then(|| secondary_account(chain, index)) + .flatten() + .map(|account| account.derivation_path.to_string()) + }) .ok_or_else(|| { debug!( - "{LOG_PREFIX} secret_material missing account chain={}", + "{LOG_PREFIX} secret_material missing account chain={} index={index}", chain.as_str() ); - format!("no wallet account derived for chain '{}'", chain.as_str()) + if index == 0 { + format!("no wallet account derived for chain '{}'", chain.as_str()) + } else { + format!( + "no wallet account derived for chain '{}' index {index}", + chain.as_str() + ) + } })?; debug!( - "{LOG_PREFIX} secret_material loaded chain={} derivation_path={}", + "{LOG_PREFIX} secret_material loaded chain={} index={index} derivation_path={}", chain.as_str(), derivation_path ); @@ -416,6 +545,91 @@ pub(crate) async fn secret_material( }) } +/// The stored account `index` of `chain`, deriving and storing it first when +/// it is a known secondary account that this wallet's state predates. +/// +/// This is the migration path for wallets imported before a secondary account +/// existed: the encrypted phrase is decrypted, the module derives the address, +/// and the account is added to the stored state. +pub async fn ensure_account( + ctx: &DispatchCtx, + chain: WalletChain, + index: u32, +) -> Result { + let config = ctx.load_config().await?; + let encrypted_mnemonic = { + let _guard = WALLET_STATE_FILE_LOCK.lock(); + let state = load_stored_wallet_state_unlocked(&config)? + .ok_or_else(|| WALLET_NOT_CONFIGURED_MESSAGE.to_string())?; + if let Some(account) = state + .accounts + .iter() + .find(|account| account.chain == chain && account.index == index) + { + return Ok(account.clone()); + } + if index == 0 || secondary_account(chain, index).is_none() { + return Err(format!( + "no wallet account '{}' index {index}; secondary accounts are: {}", + chain.as_str(), + SECONDARY_ACCOUNTS + .iter() + .map(|account| format!("{} index {}", account.chain.as_str(), account.index)) + .collect::>() + .join(", ") + )); + } + state + .encrypted_mnemonic + .as_ref() + .map(|value| value.trim().to_string()) + .filter(|value| !value.is_empty()) + .or_else(|| keychain_load_mnemonic(&config)) + .ok_or_else(|| { + "wallet secret material is missing; re-import the recovery phrase to enable signing" + .to_string() + })? + }; + let Some(planned) = derivation_plan() + .into_iter() + .find(|account| account.chain == chain && account.index == index) + else { + return Err(format!("no derivation for '{}' index {index}", chain.as_str())); + }; + let mnemonic = Zeroizing::new( + crate::credentials::ops::decrypt_secret(&config, &encrypted_mnemonic) + .await + .map_err(|error| format!("failed to decrypt the recovery phrase: {error}"))? + .value, + ); + let address = derive_address(&config, &mnemonic, chain, &planned.derivation_path).await?; + let account = WalletAccount { address, ..planned }; + + let _guard = WALLET_STATE_FILE_LOCK.lock(); + let mut state = load_stored_wallet_state_unlocked(&config)? + .ok_or_else(|| WALLET_NOT_CONFIGURED_MESSAGE.to_string())?; + if state.encrypted_mnemonic.is_some() + && state.encrypted_mnemonic.as_deref().map(str::trim) != Some(encrypted_mnemonic.as_str()) + { + return Err("the wallet changed while its account was being derived; retry".to_string()); + } + if let Some(existing) = state + .accounts + .iter() + .find(|existing| existing.chain == chain && existing.index == index) + { + return Ok(existing.clone()); + } + state.accounts.push(account.clone()); + state.updated_at_ms = state::current_time_ms(); + save_stored_wallet_state_unlocked(&config, &state)?; + debug!( + "{LOG_PREFIX} ensure_account stored chain={} index={index}", + chain.as_str() + ); + Ok(account) +} + #[cfg(test)] #[path = "ops_tests.rs"] mod tests; From 7361c86eb759d7805ef2d698217793bfe303df1d Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Sun, 15 Nov 2026 21:46:11 +0000 Subject: [PATCH 05/32] feat(config): add per-account wallet program policy Adds an `accounts` map to the wallet policy config, keyed `_`, that governs what a secondary or host-built program transaction account may sign. Each entry lists allowed program ids and per-mint caps, and an account without an entry is refused for every program execute, keeping this policy independent of the existing `assets` caps. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../openhuman-core/src/config/schema/mod.rs | 2 +- .../src/config/schema/wallet_policy.rs | 72 +++++++++++++++++++ 2 files changed, 73 insertions(+), 1 deletion(-) diff --git a/crates/openhuman-core/src/config/schema/mod.rs b/crates/openhuman-core/src/config/schema/mod.rs index e9f2a6c9ee0..019eb018c51 100644 --- a/crates/openhuman-core/src/config/schema/mod.rs +++ b/crates/openhuman-core/src/config/schema/mod.rs @@ -63,7 +63,7 @@ pub use hosting::HostingConfig; pub mod storage; pub use storage::StorageConfig; pub mod wallet_policy; -pub use wallet_policy::{WalletAssetCap, WalletPolicyConfig}; +pub use wallet_policy::{WalletAccountPolicy, WalletAssetCap, WalletMintCap, WalletPolicyConfig}; pub mod profile_layout; pub use profile_layout::{users_dir, ProfileLayout}; mod identity_cost; diff --git a/crates/openhuman-core/src/config/schema/wallet_policy.rs b/crates/openhuman-core/src/config/schema/wallet_policy.rs index 9d5ac6fc532..674edbf011d 100644 --- a/crates/openhuman-core/src/config/schema/wallet_policy.rs +++ b/crates/openhuman-core/src/config/schema/wallet_policy.rs @@ -31,12 +31,38 @@ //! recipient_weekly_max_raw = 50000000 # 50 USDC per recipient per rolling 7d //! ``` //! +//! ## Per-account program policy +//! +//! `assets` above governs the primary account of each chain, which signs the +//! module's transfers. A secondary account (Solana index 1, `m/44'/501'/1'/0'`) +//! and any account used to sign a host-built transaction through +//! `wallet.prepare_program` / `wallet.execute_prepared_program` is governed +//! only by its own section, keyed `_`. An account with no +//! section is refused for every program execute; the section never affects +//! `assets` or the primary account's transfers. +//! +//! ```toml +//! [wallet_policy.accounts.solana_1] +//! allowed_programs = [ +//! "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA", # SPL Token +//! "ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL", # Associated Token Account +//! "mERKcfxMC5SqJn4Ld4BUris3WKZZ1ojjWJ3A3J5CKxv", # merkle distributor +//! ] +//! +//! [[wallet_policy.accounts.solana_1.mints]] +//! mint = "" +//! per_tx_max_raw = 1000000000 # atomic units of the mint +//! daily_max_raw = 2000000000 # rolling 24h +//! ``` +//! //! Environment overrides (applied at config load, like every other section): //! `OPENHUMAN_WALLET_POLICY_AUTOMATION_ENABLED`, //! `OPENHUMAN_WALLET_POLICY_APPLY_TO_INTERACTIVE` (booleans) and //! `OPENHUMAN_WALLET_POLICY_ASSETS` (a JSON array of asset caps, replacing the //! `assets` list). +use std::collections::BTreeMap; + use schemars::JsonSchema; use serde::{Deserialize, Serialize}; @@ -57,6 +83,52 @@ pub struct WalletPolicyConfig { /// The assets a capped execute may move, each with its caps. An asset that /// is not listed is refused for every capped execute. pub assets: Vec, + + /// Per-account policy for host-built program transactions, keyed + /// `_` (`solana_1`). An account with no entry cannot sign a + /// program transaction. Independent of `assets`. + #[serde(skip_serializing_if = "BTreeMap::is_empty")] + pub accounts: BTreeMap, +} + +impl WalletPolicyConfig { + /// The key of `chain`'s account `index` in [`Self::accounts`]. + #[must_use] + pub fn account_key(chain: &str, index: u32) -> String { + format!("{}_{index}", chain.to_ascii_lowercase()) + } + + /// The program policy of `chain`'s account `index`, if it has one. + #[must_use] + pub fn account_policy(&self, chain: &str, index: u32) -> Option<&WalletAccountPolicy> { + self.accounts.get(&Self::account_key(chain, index)) + } +} + +/// What one account may sign through `wallet.execute_prepared_program`. +/// +/// Every instruction of the transaction must invoke a listed program, and +/// every SPL token movement must be of a listed mint within its caps. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] +#[serde(default, deny_unknown_fields)] +pub struct WalletAccountPolicy { + /// Program ids (base58) the transaction's instructions may invoke. + pub allowed_programs: Vec, + /// The mints the account may move, each with its caps. + pub mints: Vec, +} + +/// Caps for one SPL mint. Both caps are required: a program account has no +/// uncapped mode. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct WalletMintCap { + /// Mint address (base58). + pub mint: String, + /// Largest total of this mint one transaction may move, atomic units. + pub per_tx_max_raw: u64, + /// Largest total over the last 24 hours, atomic units. + pub daily_max_raw: u64, } /// The caps for one asset. A cap that is absent does not limit that dimension; From bd161c12d5ac6b95189aebcdcb1b15cca1663f86 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Sun, 15 Nov 2026 21:46:27 +0000 Subject: [PATCH 06/32] feat(wallet): track ledger record kind and account index Ledger records now carry the kind of operation that was signed and the signing account's index, so transfer and program executions no longer count against each other's caps. Policy refusals gained distinct kinds for disallowed accounts, programs, instructions, mints and transactions, and the wallet policy example no longer hardcodes a distributor program id. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../src/config/schema/wallet_policy.rs | 2 +- .../openhuman-core/src/web3/wallet/ledger.rs | 31 +++++++++++++++++++ .../openhuman-core/src/web3/wallet/policy.rs | 20 ++++++++++-- 3 files changed, 50 insertions(+), 3 deletions(-) diff --git a/crates/openhuman-core/src/config/schema/wallet_policy.rs b/crates/openhuman-core/src/config/schema/wallet_policy.rs index 674edbf011d..7371c424a4e 100644 --- a/crates/openhuman-core/src/config/schema/wallet_policy.rs +++ b/crates/openhuman-core/src/config/schema/wallet_policy.rs @@ -46,7 +46,7 @@ //! allowed_programs = [ //! "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA", # SPL Token //! "ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL", # Associated Token Account -//! "mERKcfxMC5SqJn4Ld4BUris3WKZZ1ojjWJ3A3J5CKxv", # merkle distributor +//! "", # the program being called //! ] //! //! [[wallet_policy.accounts.solana_1.mints]] diff --git a/crates/openhuman-core/src/web3/wallet/ledger.rs b/crates/openhuman-core/src/web3/wallet/ledger.rs index 5285c065f16..37c7d8dfaaf 100644 --- a/crates/openhuman-core/src/web3/wallet/ledger.rs +++ b/crates/openhuman-core/src/web3/wallet/ledger.rs @@ -65,6 +65,30 @@ impl LedgerStatus { } } +/// What an execute signed. +#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)] +#[serde(rename_all = "snake_case")] +pub enum LedgerKind { + /// A module-prepared transfer from a chain's primary account + /// (`wallet.execute_prepared`). Records written before kinds existed. + #[default] + Transfer, + /// A host-built transaction (`wallet.execute_prepared_program`), capped by + /// its account's `[wallet_policy.accounts]` section only. + Program, +} + +impl LedgerKind { + fn is_transfer(&self) -> bool { + *self == Self::Transfer + } +} + +#[allow(clippy::trivially_copy_pass_by_ref)] +fn is_zero(value: &u32) -> bool { + *value == 0 +} + /// One execute attempt. #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] #[serde(rename_all = "camelCase")] @@ -105,6 +129,13 @@ pub struct LedgerRecord { /// Why the execute was refused or failed. #[serde(default, skip_serializing_if = "Option::is_none")] pub error: Option, + /// What was signed. Transfer and program records never count against + /// each other's caps. + #[serde(default, skip_serializing_if = "LedgerKind::is_transfer")] + pub kind: LedgerKind, + /// The signing account's index on its chain (0 for the primary account). + #[serde(default, skip_serializing_if = "is_zero")] + pub account_index: u32, } impl LedgerRecord { diff --git a/crates/openhuman-core/src/web3/wallet/policy.rs b/crates/openhuman-core/src/web3/wallet/policy.rs index 637bd579d61..90e6443bb16 100644 --- a/crates/openhuman-core/src/web3/wallet/policy.rs +++ b/crates/openhuman-core/src/web3/wallet/policy.rs @@ -37,7 +37,7 @@ use crate::core::runtime::turn_origin::{AgentTurnOrigin, TrustedAutomationSource use crate::modules::wallet::WalletCallError; use tinywallet_bus::wire::{ExecutionResult, PreparedTransaction}; -use super::ledger::{LedgerRecord, LedgerStatus, SpendLedger}; +use super::ledger::{LedgerKind, LedgerRecord, LedgerStatus, SpendLedger}; /// Prefix of every policy refusal, so callers and logs can tell a refusal from /// a failure. @@ -150,6 +150,18 @@ pub enum RefusalKind { Daily, RecipientWeekly, AlreadyAttempted, + /// The account has no `[wallet_policy.accounts]` section. + AccountNotAllowed, + /// An instruction invokes a program the account's section does not list. + ProgramNotAllowed, + /// An instruction the host refuses to sign whatever the policy says (a + /// token approval, a System transfer, an unverifiable token transfer). + InstructionNotAllowed, + /// A token movement of a mint the account's section does not list. + MintNotAllowed, + /// The transaction itself cannot be signed by this account (wrong fee + /// payer, extra signers, address lookup tables, malformed bytes). + TransactionNotAllowed, } /// A refused execute. @@ -165,7 +177,7 @@ impl std::fmt::Display for PolicyRefusal { } } -fn refusal(kind: RefusalKind, message: impl Into) -> PolicyRefusal { +pub(crate) fn refusal(kind: RefusalKind, message: impl Into) -> PolicyRefusal { PolicyRefusal { kind, message: message.into(), @@ -284,6 +296,8 @@ pub fn evaluate( let counted = records.iter().filter(|record| { record.policy_applied + && record.kind == LedgerKind::Transfer + && record.account_index == 0 && record.status.counts_against_caps() && cap_matches(cap, &record_facts(record)) }); @@ -345,6 +359,8 @@ fn new_record( status, transaction_hash: None, error: None, + kind: LedgerKind::Transfer, + account_index: 0, } } From 992ede26368561b7f7251aaef39a01282b00ef6b Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Sun, 15 Nov 2026 21:46:34 +0000 Subject: [PATCH 07/32] test(wallet): update test fixtures for new ledger and policy fields The ledger test helper now populates the kind and account_index fields, and the policy test helper fills remaining config fields via default, keeping the fixtures compiling after the structs gained new members. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- crates/openhuman-core/src/web3/wallet/ledger_tests.rs | 2 ++ crates/openhuman-core/src/web3/wallet/policy_tests.rs | 1 + 2 files changed, 3 insertions(+) diff --git a/crates/openhuman-core/src/web3/wallet/ledger_tests.rs b/crates/openhuman-core/src/web3/wallet/ledger_tests.rs index d28176dc2ae..1a5dfd3db19 100644 --- a/crates/openhuman-core/src/web3/wallet/ledger_tests.rs +++ b/crates/openhuman-core/src/web3/wallet/ledger_tests.rs @@ -18,6 +18,8 @@ pub(super) fn record(quote_id: &str, created_at_ms: u64, status: LedgerStatus) - status, transaction_hash: None, error: None, + kind: LedgerKind::Transfer, + account_index: 0, } } diff --git a/crates/openhuman-core/src/web3/wallet/policy_tests.rs b/crates/openhuman-core/src/web3/wallet/policy_tests.rs index 9176fc15216..5ddb0b2bc60 100644 --- a/crates/openhuman-core/src/web3/wallet/policy_tests.rs +++ b/crates/openhuman-core/src/web3/wallet/policy_tests.rs @@ -23,6 +23,7 @@ fn policy() -> WalletPolicyConfig { automation_enabled: true, apply_to_interactive: false, assets: vec![usdc_cap()], + ..WalletPolicyConfig::default() } } From b4f17ef085151e4d123bf72bbe380b915904057e Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Sun, 15 Nov 2026 21:46:43 +0000 Subject: [PATCH 08/32] chore(web3): add bs58 dependency for transaction decoding Adds the bs58 crate as an optional dependency behind the web3 feature so the wallet program module can decode host-built Solana transactions before signing. It is a codec only and carries no key material. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- crates/openhuman-core/Cargo.toml | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/crates/openhuman-core/Cargo.toml b/crates/openhuman-core/Cargo.toml index fb762a4df26..cd49b0bad85 100644 --- a/crates/openhuman-core/Cargo.toml +++ b/crates/openhuman-core/Cargo.toml @@ -452,6 +452,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 = ["wire"], optional = true } +# Base58 for Solana public keys and signatures in `web3::wallet::program`, +# which decodes a host-built transaction to check it against the account's +# policy before the module signs it. A codec only; no key material. +bs58 = { version = "0.5", optional = true } [target.'cfg(windows)'.dependencies] @@ -721,6 +725,7 @@ voice = [ # feature carries only the lightweight bus contract and generic HTTP client. web3 = [ "dep:tinywallet-bus", + "dep:bs58", "modules", ] From 0cc43d0a97ffc8360116a6f2a47ee6597f4c11c4 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Sun, 15 Nov 2026 21:47:25 +0000 Subject: [PATCH 09/32] refactor(web3): expose execution origin label and class to crate Widened the visibility of ExecutionOrigin's label and class helpers from private to pub(crate) so other modules in the crate can reuse them when describing execution origins. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- crates/openhuman-core/src/web3/wallet/policy.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/openhuman-core/src/web3/wallet/policy.rs b/crates/openhuman-core/src/web3/wallet/policy.rs index 90e6443bb16..1a499b0b5d9 100644 --- a/crates/openhuman-core/src/web3/wallet/policy.rs +++ b/crates/openhuman-core/src/web3/wallet/policy.rs @@ -97,7 +97,7 @@ impl ExecutionOrigin { } } - fn label(&self) -> &'static str { + pub(crate) fn label(&self) -> &'static str { match self { Self::Interactive { .. } => "interactive", Self::Agent { .. } => "agent", @@ -106,7 +106,7 @@ impl ExecutionOrigin { } } - fn class(&self) -> &str { + pub(crate) fn class(&self) -> &str { match self { Self::Interactive { class } | Self::Agent { class } From ce48fca73271b99039864a418c143fca47505886 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Sun, 15 Nov 2026 21:49:02 +0000 Subject: [PATCH 10/32] feat(web3): add wallet program module Introduce a new module for wallet program handling in the web3 wallet layer, providing the foundation for program-related wallet operations. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../openhuman-core/src/web3/wallet/program.rs | 932 ++++++++++++++++++ 1 file changed, 932 insertions(+) create mode 100644 crates/openhuman-core/src/web3/wallet/program.rs diff --git a/crates/openhuman-core/src/web3/wallet/program.rs b/crates/openhuman-core/src/web3/wallet/program.rs new file mode 100644 index 00000000000..0a711f743c5 --- /dev/null +++ b/crates/openhuman-core/src/web3/wallet/program.rs @@ -0,0 +1,932 @@ +//! Host-built Solana program transactions signed by one wallet account under +//! that account's own policy: `wallet.prepare_program` and +//! `wallet.execute_prepared_program`. +//! +//! The module's transfers cover the primary account's sends. Some callers +//! need to call an on-chain program instead (a merkle distributor, say), with +//! a transaction they build themselves. This path lets them, without letting +//! them sign anything: +//! +//! 1. **Prepare.** The caller hands over an unsigned Solana transaction +//! (base64 wire bytes, legacy or v0 without address lookup tables) and the +//! account index to sign with. The host decodes it and refuses it unless +//! - the account is the fee payer and the only signer; +//! - every instruction invokes a program in the account's +//! `allowed_programs` (`[wallet_policy.accounts.solana_]`); +//! - every SPL Token / Token-2022 instruction is a `TransferChecked` (the +//! only form that names its mint), and every Associated Token Account +//! instruction is a create; no top-level System program instruction; +//! - the mint moved is listed in the account's `mints`, at most one mint +//! per transaction, within its per-transaction cap and, with the spend +//! ledger, its rolling 24-hour cap. +//! +//! It stores the exact bytes under a quote id for [`QUOTE_TTL_MS`] and +//! returns the decoded summary (programs, instructions, token movements, +//! totals) for the caller to check against what it meant to build. +//! 2. **Execute.** The caller names the quote and the account index again. +//! The host re-evaluates the policy against the ledger and reserves the +//! spend atomically (`ledger::SpendLedger::reserve`), asks the TinyWallet +//! module to sign the message bytes with the account's key (a confidential +//! `SignMessage`; the key never leaves the module), attaches the signature +//! and sends the transaction to the Solana RPC. The ledger record moves to +//! `broadcast` or `in_doubt`; a quote is never executed twice. +//! +//! Programs other than SPL Token, Token-2022 and Associated Token Account are +//! opaque here: listing one is trusting it with the account's signature. The +//! caps bound only what top-level token instructions move. +//! +//! The pure parts (decoding, summarising, the policy decision) are separate +//! functions so they are tested without a module or a chain. + +use std::collections::{BTreeMap, HashMap}; +use std::sync::Mutex; + +use base64::Engine as _; +use once_cell::sync::Lazy; +use serde::{Deserialize, Serialize}; +use tinywallet_bus::wire::{RpcEndpointKey, RpcSource, Scheme, SecretMaterial, Signature}; +use zeroize::Zeroizing; + +use crate::config::schema::WalletPolicyConfig; +use crate::core::runtime::DispatchCtx; +use crate::core::Outcome; + +use super::ledger::{LedgerKind, LedgerRecord, LedgerStatus, SpendLedger}; +use super::ops::WalletChain; +use super::policy::{origin_refusal, refusal, ExecutionOrigin, PolicyRefusal, RefusalKind}; + +/// The System program. +pub const SYSTEM_PROGRAM: &str = "11111111111111111111111111111111"; +/// SPL Token. +pub const TOKEN_PROGRAM: &str = "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA"; +/// SPL Token-2022. +pub const TOKEN_2022_PROGRAM: &str = "TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb"; +/// Associated Token Account. +pub const ASSOCIATED_TOKEN_PROGRAM: &str = "ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL"; + +/// How long a prepared program transaction stays executable. A Solana +/// blockhash expires after roughly 60-90 seconds, so a longer quote would only +/// fail at the RPC. +pub const QUOTE_TTL_MS: u64 = 60_000; +/// Largest Solana transaction on the wire. +pub const MAX_TRANSACTION_BYTES: usize = 1232; +/// Prefix of every program quote id. +pub const QUOTE_PREFIX: &str = "prog-"; + +const DAY_MS: u64 = 24 * 60 * 60 * 1000; +/// SPL Token `TransferChecked`. +const TOKEN_TRANSFER_CHECKED: u8 = 12; +const LOG_PREFIX: &str = "[wallet:program]"; + +// ── Decoding ──────────────────────────────────────────────────────────────── + +/// One compiled instruction, with indices into the message's account keys. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct CompiledInstruction { + pub program_index: u8, + pub accounts: Vec, + pub data: Vec, +} + +/// A decoded Solana transaction: the exact message bytes that are signed and +/// the parts of the message the policy reads. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct DecodedTransaction { + /// Number of signature slots on the wire. + pub signature_count: usize, + /// Byte offset of the first signature slot. + pub signatures_offset: usize, + /// The serialized message, exactly as it is signed. + pub message: Vec, + /// Whether the message is versioned (v0). + pub versioned: bool, + pub num_required_signatures: u8, + pub account_keys: Vec<[u8; 32]>, + pub recent_blockhash: [u8; 32], + pub instructions: Vec, + /// Address lookup tables a v0 message loads (always 0 for legacy). + pub lookup_table_count: usize, +} + +struct Reader<'a> { + bytes: &'a [u8], + pos: usize, +} + +impl<'a> Reader<'a> { + fn take(&mut self, len: usize) -> Result<&'a [u8], String> { + let end = self + .pos + .checked_add(len) + .filter(|end| *end <= self.bytes.len()) + .ok_or_else(|| "transaction is truncated".to_string())?; + let slice = &self.bytes[self.pos..end]; + self.pos = end; + Ok(slice) + } + + fn u8(&mut self) -> Result { + Ok(self.take(1)?[0]) + } + + fn key(&mut self) -> Result<[u8; 32], String> { + let mut key = [0u8; 32]; + key.copy_from_slice(self.take(32)?); + Ok(key) + } + + /// Solana's compact-u16 ("shortvec") length. + fn compact_u16(&mut self) -> Result { + let mut value: usize = 0; + for shift in [0u32, 7, 14] { + let byte = self.u8()?; + value |= usize::from(byte & 0x7f) << shift; + if byte & 0x80 == 0 { + if value > usize::from(u16::MAX) { + break; + } + return Ok(value); + } + } + Err("transaction has an invalid compact-u16 length".to_string()) + } +} + +/// Decode a transaction's wire bytes (signature slots followed by a legacy or +/// v0 message). +/// +/// # Errors +/// +/// Malformed, truncated, oversized or trailing bytes, or an unsupported +/// message version. +pub fn decode_transaction(bytes: &[u8]) -> Result { + if bytes.len() > MAX_TRANSACTION_BYTES { + return Err(format!( + "transaction is {} bytes; the Solana limit is {MAX_TRANSACTION_BYTES}", + bytes.len() + )); + } + let mut reader = Reader { bytes, pos: 0 }; + let signature_count = reader.compact_u16()?; + let signatures_offset = reader.pos; + reader.take(signature_count.checked_mul(64).ok_or("too many signatures")?)?; + let message_start = reader.pos; + + let first = *bytes + .get(message_start) + .ok_or_else(|| "transaction has no message".to_string())?; + let versioned = first & 0x80 != 0; + if versioned { + let version = reader.u8()? & 0x7f; + if version != 0 { + return Err(format!("unsupported transaction message version {version}")); + } + } + let num_required_signatures = reader.u8()?; + let _num_readonly_signed = reader.u8()?; + let _num_readonly_unsigned = reader.u8()?; + let key_count = reader.compact_u16()?; + let account_keys = (0..key_count) + .map(|_| reader.key()) + .collect::, _>>()?; + let recent_blockhash = reader.key()?; + let instruction_count = reader.compact_u16()?; + let mut instructions = Vec::with_capacity(instruction_count); + for _ in 0..instruction_count { + let program_index = reader.u8()?; + let account_count = reader.compact_u16()?; + let accounts = reader.take(account_count)?.to_vec(); + let data_len = reader.compact_u16()?; + let data = reader.take(data_len)?.to_vec(); + instructions.push(CompiledInstruction { + program_index, + accounts, + data, + }); + } + let lookup_table_count = if versioned { + let count = reader.compact_u16()?; + for _ in 0..count { + reader.key()?; + let writable = reader.compact_u16()?; + reader.take(writable)?; + let readonly = reader.compact_u16()?; + reader.take(readonly)?; + } + count + } else { + 0 + }; + if reader.pos != bytes.len() { + return Err("transaction has trailing bytes after the message".to_string()); + } + Ok(DecodedTransaction { + signature_count, + signatures_offset, + message: bytes[message_start..].to_vec(), + versioned, + num_required_signatures, + account_keys, + recent_blockhash, + instructions, + lookup_table_count, + }) +} + +/// `bytes` with signature slot 0 replaced by `signature`. +/// +/// # Errors +/// +/// When the transaction has no signature slot. +pub fn attach_signature( + bytes: &[u8], + decoded: &DecodedTransaction, + signature: &[u8; 64], +) -> Result, String> { + if decoded.signature_count == 0 { + return Err("transaction has no signature slot".to_string()); + } + let mut signed = bytes.to_vec(); + signed[decoded.signatures_offset..decoded.signatures_offset + 64].copy_from_slice(signature); + Ok(signed) +} + +fn base58(bytes: &[u8]) -> String { + bs58::encode(bytes).into_string() +} + +// ── Summary ───────────────────────────────────────────────────────────────── + +/// One instruction, decoded to addresses. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct InstructionSummary { + pub program_id: String, + pub accounts: Vec, + /// Lowercase hex of the instruction data, for the caller to check + /// program-specific arguments (a merkle root, an amount) it built. + pub data_hex: String, +} + +/// One SPL `TransferChecked`. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct TokenMovement { + pub program_id: String, + pub mint: String, + pub source: String, + pub destination: String, + pub authority: String, + /// Atomic units, decimal string. + pub amount_raw: String, + pub decimals: u8, +} + +/// The total a transaction moves of one mint. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct MintTotal { + pub mint: String, + /// Atomic units, decimal string. + pub amount_raw: String, +} + +/// What a prepared program transaction does, as the host decoded it. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ProgramTransactionSummary { + /// The fee payer and only signer: the signing account's address. + pub fee_payer: String, + pub recent_blockhash: String, + /// Distinct program ids, in first-use order. + pub programs: Vec, + pub instructions: Vec, + /// Every top-level SPL token movement. + pub movements: Vec, + /// Per-mint totals of `movements`. + pub totals: Vec, +} + +fn structural(message: impl Into) -> PolicyRefusal { + refusal(RefusalKind::TransactionNotAllowed, message) +} + +fn forbidden(message: impl Into) -> PolicyRefusal { + refusal(RefusalKind::InstructionNotAllowed, message) +} + +/// Decode `tx` into its summary and check what the host refuses whatever the +/// policy says: `signer` must be the fee payer and the only signer, no lookup +/// tables, and only the token, ATA and System instructions this path can +/// account for. +/// +/// # Errors +/// +/// The refusal. +pub fn summarize( + tx: &DecodedTransaction, + signer: &str, +) -> Result { + if tx.lookup_table_count > 0 { + return Err(structural( + "transactions that load address lookup tables are not supported; \ + list every account in the message", + )); + } + if tx.num_required_signatures != 1 || tx.signature_count != 1 { + return Err(structural(format!( + "the transaction needs {} signatures over {} slots; only a transaction the \ + account signs alone is supported", + tx.num_required_signatures, tx.signature_count + ))); + } + let fee_payer = tx + .account_keys + .first() + .map(|key| base58(key)) + .ok_or_else(|| structural("the transaction lists no accounts"))?; + if fee_payer != signer { + return Err(structural(format!( + "the fee payer {fee_payer} is not the signing account {signer}" + ))); + } + + let key = |index: u8| -> Result { + tx.account_keys + .get(usize::from(index)) + .map(|key| base58(key)) + .ok_or_else(|| structural(format!("account index {index} is out of range"))) + }; + + let mut programs: Vec = Vec::new(); + let mut instructions = Vec::with_capacity(tx.instructions.len()); + let mut movements = Vec::new(); + let mut totals: BTreeMap = BTreeMap::new(); + let mut mint_order: Vec = Vec::new(); + for (position, instruction) in tx.instructions.iter().enumerate() { + let program_id = key(instruction.program_index)?; + let accounts = instruction + .accounts + .iter() + .map(|index| key(*index)) + .collect::, _>>()?; + match program_id.as_str() { + SYSTEM_PROGRAM => { + return Err(forbidden(format!( + "instruction {position} calls the System program; native SOL movements \ + are not signed through program executes" + ))); + } + TOKEN_PROGRAM | TOKEN_2022_PROGRAM => { + let movement = token_transfer_checked(position, &program_id, instruction, &accounts)?; + let amount: u128 = movement.amount_raw.parse().unwrap_or(u128::MAX); + let total = totals.entry(movement.mint.clone()).or_insert_with(|| { + mint_order.push(movement.mint.clone()); + 0 + }); + *total = total.saturating_add(amount); + movements.push(movement); + } + ASSOCIATED_TOKEN_PROGRAM => { + // Create (empty data or 0) and CreateIdempotent (1) only; + // RecoverNested moves tokens. + if !matches!(instruction.data.as_slice(), [] | [0] | [1]) { + return Err(forbidden(format!( + "instruction {position} is not an associated token account create" + ))); + } + } + _ => {} + } + if !programs.contains(&program_id) { + programs.push(program_id.clone()); + } + instructions.push(InstructionSummary { + program_id, + accounts, + data_hex: hex::encode(&instruction.data), + }); + } + let totals = mint_order + .into_iter() + .map(|mint| MintTotal { + amount_raw: totals.get(&mint).copied().unwrap_or_default().to_string(), + mint, + }) + .collect(); + Ok(ProgramTransactionSummary { + fee_payer, + recent_blockhash: base58(&tx.recent_blockhash), + programs, + instructions, + movements, + totals, + }) +} + +fn token_transfer_checked( + position: usize, + program_id: &str, + instruction: &CompiledInstruction, + accounts: &[String], +) -> Result { + match instruction.data.first() { + Some(&TOKEN_TRANSFER_CHECKED) => {} + Some(3) => { + return Err(forbidden(format!( + "instruction {position} is a token Transfer, which does not name its mint; \ + use TransferChecked" + ))) + } + other => { + return Err(forbidden(format!( + "instruction {position} is token instruction {other:?}; only TransferChecked \ + is signed through program executes" + ))) + } + } + if instruction.data.len() != 10 || accounts.len() < 4 { + return Err(structural(format!( + "instruction {position} is a malformed TransferChecked" + ))); + } + let mut amount = [0u8; 8]; + amount.copy_from_slice(&instruction.data[1..9]); + Ok(TokenMovement { + program_id: program_id.to_string(), + source: accounts[0].clone(), + mint: accounts[1].clone(), + destination: accounts[2].clone(), + authority: accounts[3].clone(), + amount_raw: u64::from_le_bytes(amount).to_string(), + decimals: instruction.data[9], + }) +} + +// ── Policy ────────────────────────────────────────────────────────────────── + +/// Decide whether `chain`'s account `account_index` may sign a transaction +/// with `summary`, given the ledger `records`. +/// +/// # Errors +/// +/// The refusal, naming the rule and the amounts. +pub fn evaluate_program( + policy: &WalletPolicyConfig, + chain: &str, + account_index: u32, + summary: &ProgramTransactionSummary, + records: &[LedgerRecord], + now_ms: u64, +) -> Result<(), PolicyRefusal> { + let key = WalletPolicyConfig::account_key(chain, account_index); + let Some(section) = policy.account_policy(chain, account_index) else { + return Err(refusal( + RefusalKind::AccountNotAllowed, + format!("account {key} has no [wallet_policy.accounts.{key}] section"), + )); + }; + if let Some(program) = summary + .programs + .iter() + .find(|program| !section.allowed_programs.iter().any(|allowed| allowed == *program)) + { + return Err(refusal( + RefusalKind::ProgramNotAllowed, + format!("program {program} is not in {key}'s allowed_programs"), + )); + } + if summary.totals.len() > 1 { + return Err(structural(format!( + "the transaction moves {} mints; a program execute may move at most one", + summary.totals.len() + ))); + } + let Some(total) = summary.totals.first() else { + return Ok(()); + }; + let Some(cap) = section.mints.iter().find(|cap| cap.mint == total.mint) else { + return Err(refusal( + RefusalKind::MintNotAllowed, + format!("mint {} is not in {key}'s mints", total.mint), + )); + }; + let amount: u128 = total.amount_raw.parse().unwrap_or(u128::MAX); + if amount > u128::from(cap.per_tx_max_raw) { + return Err(refusal( + RefusalKind::PerTransaction, + format!( + "{amount} of mint {} (atomic) exceeds {key}'s per-transaction cap of {}", + total.mint, cap.per_tx_max_raw + ), + )); + } + let since = now_ms.saturating_sub(DAY_MS); + let spent = records + .iter() + .filter(|record| { + record.kind == LedgerKind::Program + && record.account_index == account_index + && record.chain.eq_ignore_ascii_case(chain) + && record.status.counts_against_caps() + && record.token_address.as_deref() == Some(total.mint.as_str()) + && record.created_at_ms >= since + }) + .fold(0u128, |sum, record| sum.saturating_add(record.amount())); + if spent.saturating_add(amount) > u128::from(cap.daily_max_raw) { + return Err(refusal( + RefusalKind::Daily, + format!( + "{amount} of mint {} (atomic) would exceed {key}'s rolling 24h cap of {} \ + ({spent} already spent)", + total.mint, cap.daily_max_raw + ), + )); + } + Ok(()) +} + +// ── Quotes ────────────────────────────────────────────────────────────────── + +/// A prepared program transaction, as returned to the caller. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct PreparedProgram { + pub quote_id: String, + pub chain: WalletChain, + pub account_index: u32, + /// The signing account's address (the fee payer). + pub address: String, + pub summary: ProgramTransactionSummary, + pub created_at_ms: u64, + pub expires_at_ms: u64, +} + +/// The result of executing a prepared program transaction. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ExecutedProgram { + pub quote_id: String, + pub chain: WalletChain, + pub account_index: u32, + pub address: String, + /// The transaction signature (base58), as the RPC accepted it. + pub transaction_hash: String, +} + +/// `wallet.prepare_program` parameters. +#[derive(Debug, Clone, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct PrepareProgramParams { + #[serde(alias = "account_index")] + pub account_index: u32, + /// Base64 of the unsigned transaction's wire bytes (signature slots + /// zeroed), e.g. `transaction.serialize({requireAllSignatures: false})`. + pub transaction: String, +} + +/// `wallet.execute_prepared_program` parameters. +#[derive(Debug, Clone, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct ExecuteProgramParams { + #[serde(alias = "account_index")] + pub account_index: u32, + #[serde(alias = "quote_id")] + pub quote_id: String, +} + +#[derive(Clone)] +struct StoredQuote { + prepared: PreparedProgram, + transaction: Vec, + decoded: DecodedTransaction, +} + +static QUOTES: Lazy>> = Lazy::new(|| Mutex::new(HashMap::new())); + +fn store_quote(quote: StoredQuote, now_ms: u64) { + if let Ok(mut quotes) = QUOTES.lock() { + quotes.retain(|_, stored| stored.prepared.expires_at_ms > now_ms); + quotes.insert(quote.prepared.quote_id.clone(), quote); + } +} + +fn take_quote(quote_id: &str) -> Option { + QUOTES.lock().ok()?.remove(quote_id) +} + +/// Prepare quotes currently held (test support). +#[cfg(test)] +pub(crate) fn has_quote_for_test(quote_id: &str) -> bool { + QUOTES + .lock() + .is_ok_and(|quotes| quotes.contains_key(quote_id)) +} + +fn chain_name(chain: WalletChain) -> &'static str { + chain.as_str() +} + +fn ledger_records(config: &crate::config::Config) -> Result<(SpendLedger, Vec), String> { + let ledger = SpendLedger::open(&config.workspace_dir) + .map_err(|error| format!("wallet spend ledger is unavailable: {error:#}"))?; + let records = ledger + .records() + .map_err(|error| format!("wallet spend ledger is unavailable: {error:#}"))?; + Ok((ledger, records)) +} + +/// Decode, summarise and check one transaction, then store it as a quote. +/// The policy section is checked before any key derivation. +/// +/// # Errors +/// +/// A policy refusal (prefixed `WALLET_POLICY_REFUSED:`), malformed input, or +/// a wallet that cannot provide the account. +pub async fn prepare_program( + ctx: &DispatchCtx, + params: PrepareProgramParams, +) -> Result, String> { + let chain = WalletChain::Solana; + let config = ctx.load_config().await?; + let key = WalletPolicyConfig::account_key(chain_name(chain), params.account_index); + if config + .wallet_policy + .account_policy(chain_name(chain), params.account_index) + .is_none() + { + return Err(refusal( + RefusalKind::AccountNotAllowed, + format!("account {key} has no [wallet_policy.accounts.{key}] section"), + ) + .to_string()); + } + let transaction = base64::engine::general_purpose::STANDARD + .decode(params.transaction.trim()) + .map_err(|error| format!("transaction is not valid base64: {error}"))?; + let decoded = decode_transaction(&transaction)?; + let account = super::ops::ensure_account(ctx, chain, params.account_index).await?; + let summary = summarize(&decoded, &account.address).map_err(|refused| refused.to_string())?; + let now = super::policy::wall_clock_ms(); + let (_, records) = ledger_records(&config)?; + evaluate_program( + &config.wallet_policy, + chain_name(chain), + params.account_index, + &summary, + &records, + now, + ) + .map_err(|refused| { + tracing::info!(account = %key, kind = ?refused.kind, "{LOG_PREFIX} prepare refused"); + refused.to_string() + })?; + let prepared = PreparedProgram { + quote_id: format!("{QUOTE_PREFIX}{}", uuid::Uuid::new_v4()), + chain, + account_index: params.account_index, + address: account.address, + summary, + created_at_ms: now, + expires_at_ms: now + QUOTE_TTL_MS, + }; + tracing::info!( + quote_id = %prepared.quote_id, + account = %key, + programs = prepared.summary.programs.len(), + movements = prepared.summary.movements.len(), + "{LOG_PREFIX} prepared" + ); + store_quote( + StoredQuote { + prepared: prepared.clone(), + transaction, + decoded, + }, + now, + ); + Ok(Outcome::new( + prepared, + vec!["wallet program transaction prepared".to_string()], + )) +} + +/// The ledger record of one program execute. +fn program_record( + prepared: &PreparedProgram, + origin: &ExecutionOrigin, + status: LedgerStatus, + now_ms: u64, +) -> LedgerRecord { + let total = prepared.summary.totals.first(); + let destination = match prepared.summary.movements.as_slice() { + [] => String::new(), + [only] => only.destination.clone(), + [first, rest @ ..] if rest.iter().all(|m| m.destination == first.destination) => { + first.destination.clone() + } + _ => "multiple".to_string(), + }; + LedgerRecord { + id: uuid::Uuid::new_v4().to_string(), + quote_id: prepared.quote_id.clone(), + created_at_ms: now_ms, + updated_at_ms: now_ms, + origin: origin.label().into(), + origin_class: origin.class().into(), + policy_applied: true, + chain: chain_name(prepared.chain).to_string(), + evm_network: None, + asset_symbol: if total.is_some() { "SPL" } else { "" }.to_string(), + token_address: total.map(|total| total.mint.clone()), + to_address: destination, + amount_raw: total.map_or_else(|| "0".to_string(), |total| total.amount_raw.clone()), + status, + transaction_hash: None, + error: None, + kind: LedgerKind::Program, + account_index: prepared.account_index, + } +} + +/// Execute a prepared program transaction: re-check and reserve under the +/// policy, sign in the module, send. A quote is single-use once an attempt +/// reached signing. +/// +/// # Errors +/// +/// A policy refusal (prefixed `WALLET_POLICY_REFUSED:`), an unknown or +/// expired quote, or the signing or send error (the attempt is then recorded +/// `in_doubt` and never retried). +pub async fn execute_prepared_program( + ctx: &DispatchCtx, + params: ExecuteProgramParams, +) -> Result, String> { + let config = ctx.load_config().await?; + let now = super::policy::wall_clock_ms(); + let stored = take_quote(¶ms.quote_id) + .filter(|stored| stored.prepared.expires_at_ms > now) + .ok_or_else(|| "prepared program quote is unavailable or expired".to_string())?; + if stored.prepared.account_index != params.account_index { + let message = format!( + "quote {} was prepared for account index {}, not {}", + params.quote_id, stored.prepared.account_index, params.account_index + ); + store_quote(stored, now); + return Err(message); + } + let origin = ExecutionOrigin::rpc(); + let prepared = stored.prepared.clone(); + let chain = chain_name(prepared.chain); + let (ledger, _) = ledger_records(&config)?; + let reserved = ledger + .reserve(|records| { + if let Some(refused) = origin_refusal(&origin) { + return Err(refused); + } + if let Some(earlier) = records.iter().rev().find(|record| { + record.quote_id == prepared.quote_id && record.status.counts_against_caps() + }) { + return Err(refusal( + RefusalKind::AlreadyAttempted, + format!( + "quote {} was already executed (status {:?}); it is never retried", + prepared.quote_id, earlier.status + ), + )); + } + evaluate_program( + &config.wallet_policy, + chain, + prepared.account_index, + &prepared.summary, + records, + now, + )?; + Ok(program_record(&prepared, &origin, LedgerStatus::Pending, now)) + }) + .map_err(|error| format!("wallet spend ledger is unavailable: {error:#}"))?; + let mut record = match reserved { + Ok(record) => record, + Err(refused) => { + tracing::info!( + quote_id = %prepared.quote_id, + kind = ?refused.kind, + "{LOG_PREFIX} execute refused" + ); + let mut record = program_record(&prepared, &origin, LedgerStatus::Refused, now); + record.error = Some(refused.message.clone()); + if let Err(error) = ledger.put(&record) { + tracing::warn!(%error, "{LOG_PREFIX} could not record a refusal"); + } + if refused.kind != RefusalKind::AlreadyAttempted { + store_quote(stored, now); + } + return Err(refused.to_string()); + } + }; + tracing::info!( + quote_id = %prepared.quote_id, + record_id = %record.id, + "{LOG_PREFIX} execute recorded as pending" + ); + + let result = sign_and_send(ctx, &config, &stored).await; + record.updated_at_ms = super::policy::wall_clock_ms().max(now); + match &result { + Ok(hash) => { + record.status = LedgerStatus::Broadcast; + record.transaction_hash = Some(hash.clone()); + } + Err(error) => { + record.status = LedgerStatus::InDoubt; + record.error = Some(error.clone()); + } + } + if let Err(error) = ledger.put(&record) { + tracing::warn!(%error, record_id = %record.id, "{LOG_PREFIX} could not update the ledger"); + } + let transaction_hash = result?; + Ok(Outcome::new( + ExecutedProgram { + quote_id: prepared.quote_id, + chain: prepared.chain, + account_index: prepared.account_index, + address: prepared.address, + transaction_hash, + }, + vec!["wallet program transaction broadcast".to_string()], + )) +} + +async fn sign_and_send( + ctx: &DispatchCtx, + config: &crate::config::Config, + stored: &StoredQuote, +) -> Result { + let prepared = &stored.prepared; + let material = + super::ops::secret_material(ctx, prepared.chain, prepared.account_index).await?; + let mnemonic = Zeroizing::new( + crate::credentials::ops::decrypt_secret(config, &material.encrypted_mnemonic) + .await + .map_err(|error| format!("failed to decrypt the recovery phrase: {error}"))? + .value, + ); + let secret = SecretMaterial { + mnemonic: mnemonic.to_string(), + derivation_path: material.derivation_path, + chain: prepared.chain.to_chain(), + }; + let signed = crate::modules::wallet::sign_message( + config, + &secret, + &stored.decoded.message, + Scheme::Ed25519, + ) + .await; + let mut secret = secret; + zeroize::Zeroize::zeroize(&mut secret.mnemonic); + let signature = match signed.map_err(|error| error.to_string())? { + Signature::Ed25519 { signature_hex } => { + let bytes = hex::decode(signature_hex.trim()) + .map_err(|_| "wallet module returned a malformed signature".to_string())?; + <[u8; 64]>::try_from(bytes.as_slice()) + .map_err(|_| "wallet module returned a signature of the wrong length".to_string())? + } + _ => return Err("wallet module returned a non-ed25519 signature".to_string()), + }; + let signed_transaction = attach_signature(&stored.transaction, &stored.decoded, &signature)?; + let url = solana_rpc_url(ctx).await?; + let encoded = base64::engine::general_purpose::STANDARD.encode(signed_transaction); + let hash: String = super::rpc::rpc_call_to( + &url, + "sendTransaction", + serde_json::json!([encoded, {"encoding": "base64", "preflightCommitment": "confirmed"}]), + ) + .await?; + let expected = base58(&signature); + if hash != expected { + tracing::warn!("{LOG_PREFIX} RPC returned a signature other than the one attached"); + } + Ok(hash) +} + +/// The Solana endpoint: the host override when one is configured, otherwise +/// the module's default for the configured cluster. +async fn solana_rpc_url(ctx: &DispatchCtx) -> Result { + if let Some(url) = super::endpoints::override_for_endpoint(RpcEndpointKey::Solana) { + return Ok(url); + } + super::execution::network_defaults(ctx) + .await? + .value + .into_iter() + .find(|row| row.chain == WalletChain::Solana && row.rpc_source == RpcSource::Default) + .map(|row| row.rpc_url) + .ok_or_else(|| "the wallet module reports no default Solana endpoint".to_string()) +} + +#[cfg(test)] +#[path = "program_tests.rs"] +mod tests; From 57543fafbdb99c8457219502ffe8e34bceeb6e12 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Sun, 15 Nov 2026 21:49:13 +0000 Subject: [PATCH 11/32] feat(wallet): add account index to secret material lookup Thread an account index through the wallet secret material lookup so callers can request material for a specific derived account, defaulting existing call sites to index zero. Also expose the program transaction module and the ensure_account helper from the wallet module. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- crates/openhuman-core/src/modules/wallet_service.rs | 2 +- crates/openhuman-core/src/modules/web3_service.rs | 2 +- crates/openhuman-core/src/modules/x402_service.rs | 2 +- crates/openhuman-core/src/web3/wallet/mod.rs | 6 +++++- crates/openhuman-core/src/web3/wallet/stub.rs | 5 ++++- crates/openhuman-core/src/web3/wallet/stub_tests.rs | 2 +- 6 files changed, 13 insertions(+), 6 deletions(-) diff --git a/crates/openhuman-core/src/modules/wallet_service.rs b/crates/openhuman-core/src/modules/wallet_service.rs index d24cdf0442d..58218ade80c 100644 --- a/crates/openhuman-core/src/modules/wallet_service.rs +++ b/crates/openhuman-core/src/modules/wallet_service.rs @@ -266,7 +266,7 @@ async fn signing_secret( 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(ctx, local_chain) + let stored = crate::web3::wallet::secret_material(ctx, local_chain, 0) .await .map_err(WalletCallError::Failed)?; let mnemonic = crate::credentials::ops::decrypt_secret(config, &stored.encrypted_mnemonic) diff --git a/crates/openhuman-core/src/modules/web3_service.rs b/crates/openhuman-core/src/modules/web3_service.rs index 8a8dcce0f93..3f363ad8e73 100644 --- a/crates/openhuman-core/src/modules/web3_service.rs +++ b/crates/openhuman-core/src/modules/web3_service.rs @@ -253,7 +253,7 @@ pub(crate) async fn execute( WalletChain::Solana => crate::web3::wallet::WalletChain::Solana, WalletChain::Tron => crate::web3::wallet::WalletChain::Tron, }; - let stored = crate::web3::wallet::secret_material(ctx, chain) + let stored = crate::web3::wallet::secret_material(ctx, chain, 0) .await .map_err(|error| wallet::WalletCallError::Failed(error.to_string()))?; let mnemonic = crate::credentials::ops::decrypt_secret(config, &stored.encrypted_mnemonic) diff --git a/crates/openhuman-core/src/modules/x402_service.rs b/crates/openhuman-core/src/modules/x402_service.rs index 80d146e684e..c42fb7b6972 100644 --- a/crates/openhuman-core/src/modules/x402_service.rs +++ b/crates/openhuman-core/src/modules/x402_service.rs @@ -170,7 +170,7 @@ async fn signing_secret( config: &Config, chain: crate::web3::wallet::WalletChain, ) -> Result { - let stored = crate::web3::wallet::secret_material(ctx, chain) + let stored = crate::web3::wallet::secret_material(ctx, chain, 0) .await .map_err(WalletCallError::Failed)?; let phrase = crate::credentials::ops::decrypt_secret(config, &stored.encrypted_mnemonic) diff --git a/crates/openhuman-core/src/web3/wallet/mod.rs b/crates/openhuman-core/src/web3/wallet/mod.rs index f336d8d3ff8..23a22a9ceb6 100644 --- a/crates/openhuman-core/src/web3/wallet/mod.rs +++ b/crates/openhuman-core/src/web3/wallet/mod.rs @@ -48,6 +48,10 @@ mod ops; pub mod policy; #[cfg(feature = "web3")] pub mod policy_ops; +/// Host-built program transactions signed by one account under its own +/// policy (`prepare_program` / `execute_prepared_program`). +#[cfg(feature = "web3")] +pub mod program; #[cfg(feature = "web3")] pub(crate) mod rpc; @@ -72,7 +76,7 @@ pub use execution::{ }; #[cfg(feature = "web3")] pub use ops::{ - derive_recovery_material, generate_recovery_phrase, reveal_recovery_phrase, setup, status, + derive_recovery_material, ensure_account, generate_recovery_phrase, reveal_recovery_phrase, setup, status, validate_recovery_phrase, GeneratedRecoveryPhrase, RecoveryPhraseValidation, RevealRecoveryPhraseResult, WalletAccount, WalletChain, WalletRecoveryMaterial, WalletSetupParams, WalletSetupSource, WalletStatus, WALLET_NOT_CONFIGURED_MESSAGE, diff --git a/crates/openhuman-core/src/web3/wallet/stub.rs b/crates/openhuman-core/src/web3/wallet/stub.rs index 2179480c8be..8aaa8c22320 100644 --- a/crates/openhuman-core/src/web3/wallet/stub.rs +++ b/crates/openhuman-core/src/web3/wallet/stub.rs @@ -84,7 +84,10 @@ pub async fn status() -> Result, String> { /// Always errors: secret material cannot be produced with the wallet compiled /// out. Callers `?`-propagate (wallet-signed writes surface the disabled error). -pub(crate) async fn secret_material(_chain: WalletChain) -> Result { +pub(crate) async fn secret_material( + _chain: WalletChain, + _index: u32, +) -> Result { log::debug!( "[wallet-stub] secret_material requested (web3 disabled) — returning disabled error" ); diff --git a/crates/openhuman-core/src/web3/wallet/stub_tests.rs b/crates/openhuman-core/src/web3/wallet/stub_tests.rs index 9d888d4587a..97f6094a1d7 100644 --- a/crates/openhuman-core/src/web3/wallet/stub_tests.rs +++ b/crates/openhuman-core/src/web3/wallet/stub_tests.rs @@ -13,7 +13,7 @@ async fn status_reports_no_accounts() { async fn secret_material_is_disabled_error() { // `WalletSecretMaterial` intentionally omits `Debug` (mirrors the real // type, which never logs a mnemonic), so match rather than `expect_err`. - match secret_material(WalletChain::Evm).await { + match secret_material(WalletChain::Evm, 0).await { Ok(_) => panic!("secret material must be unavailable when the wallet is compiled out"), Err(msg) => assert_eq!(msg, DISABLED_MSG), } From 3edb0e1390fc88dbae203cb8c4ca3c8eb1146938 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Sun, 15 Nov 2026 21:50:01 +0000 Subject: [PATCH 12/32] feat(wallet): add account and Solana program transaction controllers Expose wallet.account, wallet.prepare_program and wallet.execute_prepared_program as registered controllers so callers can read a derived account and run policy-checked Solana transactions. The account handler derives and stores a known secondary account that predates the stored wallet state, while prepared programs are quoted for 60 seconds and re-checked against policy before signing and broadcasting. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- Cargo.lock | 1 + .../openhuman-core/src/web3/wallet/schemas.rs | 103 ++++++++++++++++++ .../src/web3/wallet/schemas_tests.rs | 7 +- 3 files changed, 109 insertions(+), 2 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 6b8af974616..a898b4d9085 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5684,6 +5684,7 @@ dependencies = [ "async-trait", "axum", "base64 0.22.1", + "bs58", "bytes", "chrono", "chrono-tz", diff --git a/crates/openhuman-core/src/web3/wallet/schemas.rs b/crates/openhuman-core/src/web3/wallet/schemas.rs index c3be53b626d..3838bb40475 100644 --- a/crates/openhuman-core/src/web3/wallet/schemas.rs +++ b/crates/openhuman-core/src/web3/wallet/schemas.rs @@ -90,6 +90,9 @@ pub fn all_wallet_controller_schemas() -> Vec { wallet_schemas("policy_get"), wallet_schemas("policy_update"), wallet_schemas("ledger_list"), + wallet_schemas("account"), + wallet_schemas("prepare_program"), + wallet_schemas("execute_prepared_program"), ] } @@ -175,6 +178,18 @@ pub fn all_wallet_registered_controllers() -> Vec { schema: wallet_schemas("ledger_list"), handler: handle_ledger_list, }, + RegisteredController { + schema: wallet_schemas("account"), + handler: handle_account, + }, + RegisteredController { + schema: wallet_schemas("prepare_program"), + handler: handle_prepare_program, + }, + RegisteredController { + schema: wallet_schemas("execute_prepared_program"), + handler: handle_execute_prepared_program, + }, ] } @@ -486,6 +501,51 @@ pub fn wallet_schemas(function: &str) -> ControllerSchema { required: true, }], }, + "account" => ControllerSchema { + namespace: "wallet", + function: "account", + description: "Read one wallet account by chain and index. A known secondary account (Solana index 1, m/44'/501'/1'/0', label giveaway) that this wallet's stored state predates is derived from the encrypted recovery phrase and stored first.", + inputs: vec![ + required_json("chain", "Chain family (evm | btc | solana | tron)."), + required_json("accountIndex", "Account index on the chain; 0 is the primary account."), + ], + outputs: vec![FieldSchema { + name: "result", + ty: TypeSchema::Json, + comment: "{chain, address, derivationPath, index?, label?}.", + required: true, + }], + }, + "prepare_program" => ControllerSchema { + namespace: "wallet", + function: "prepare_program", + description: "Check a host-built unsigned Solana transaction against [wallet_policy.accounts.solana_] and hold it as a quote for 60 seconds. Refused (WALLET_POLICY_REFUSED:) unless the account has a section, is the fee payer and only signer, every instruction invokes an allowed program, token instructions are TransferChecked of one listed mint within its per-transaction and rolling 24h caps, ATA instructions are creates, and there is no System program instruction or address lookup table.", + inputs: vec![ + required_json("accountIndex", "Index of the Solana account that signs (1 is m/44'/501'/1'/0')."), + required_json("transaction", "Base64 of the unsigned transaction's wire bytes (legacy or v0, signature slots zeroed)."), + ], + outputs: vec![FieldSchema { + name: "result", + ty: TypeSchema::Json, + comment: "{quoteId, chain, accountIndex, address, createdAtMs, expiresAtMs, summary: {feePayer, recentBlockhash, programs, instructions: [{programId, accounts, dataHex}], movements: [{programId, mint, source, destination, authority, amountRaw, decimals}], totals: [{mint, amountRaw}]}}.", + required: true, + }], + }, + "execute_prepared_program" => ControllerSchema { + namespace: "wallet", + function: "execute_prepared_program", + description: "Sign a prepared program transaction with the account's key inside the wallet module and send it to the Solana RPC. The policy is re-checked and the spend reserved in the ledger first; the attempt is recorded broadcast or in_doubt and a quote is never executed twice.", + inputs: vec![ + required_json("accountIndex", "The account index the quote was prepared for."), + required_json("quoteId", "quoteId returned by wallet.prepare_program."), + ], + outputs: vec![FieldSchema { + name: "result", + ty: TypeSchema::Json, + comment: "{quoteId, chain, accountIndex, address, transactionHash}.", + required: true, + }], + }, _ => ControllerSchema { namespace: "wallet", function: "unknown", @@ -696,6 +756,49 @@ fn handle_ledger_list(ctx: DispatchCtx, params: Map) -> Controlle }) } +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct AccountParams { + chain: WalletChain, + #[serde(alias = "account_index")] + account_index: u32, +} + +fn handle_account(ctx: DispatchCtx, params: Map) -> ControllerFuture { + Box::pin(async move { + let parsed: AccountParams = serde_json::from_value(Value::Object(params)) + .map_err(|e| format!("invalid params: {e}"))?; + let account = + crate::web3::wallet::ensure_account(&ctx, parsed.chain, parsed.account_index).await?; + serde_json::to_value(account).map_err(|e| format!("failed to encode account: {e}")) + }) +} + +fn handle_prepare_program(ctx: DispatchCtx, params: Map) -> ControllerFuture { + Box::pin(async move { + let parsed: super::program::PrepareProgramParams = + serde_json::from_value(Value::Object(params)) + .map_err(|e| format!("invalid params: {e}"))?; + super::program::prepare_program(&ctx, parsed) + .await? + .into_cli_compatible_json() + }) +} + +fn handle_execute_prepared_program( + ctx: DispatchCtx, + params: Map, +) -> ControllerFuture { + Box::pin(async move { + let parsed: super::program::ExecuteProgramParams = + serde_json::from_value(Value::Object(params)) + .map_err(|e| format!("invalid params: {e}"))?; + super::program::execute_prepared_program(&ctx, parsed) + .await? + .into_cli_compatible_json() + }) +} + /// Shared input schema for the tx_status / tx_receipt / lookup_tx readers. fn tx_query_inputs() -> Vec { vec![ diff --git a/crates/openhuman-core/src/web3/wallet/schemas_tests.rs b/crates/openhuman-core/src/web3/wallet/schemas_tests.rs index f3ab812ac63..2c853a8687e 100644 --- a/crates/openhuman-core/src/web3/wallet/schemas_tests.rs +++ b/crates/openhuman-core/src/web3/wallet/schemas_tests.rs @@ -6,8 +6,8 @@ use crate::core::all::{ #[test] fn wallet_schema_wire_contracts_are_preserved() { - assert_eq!(all_wallet_controller_schemas().len(), 20); - assert_eq!(all_wallet_registered_controllers().len(), 20); + assert_eq!(all_wallet_controller_schemas().len(), 23); + assert_eq!(all_wallet_registered_controllers().len(), 23); assert_schema_controller_parity( &all_wallet_controller_schemas(), &all_wallet_registered_controllers(), @@ -20,6 +20,9 @@ fn wallet_schema_wire_contracts_are_preserved() { ("derive_recovery_material", &["phrase"][..]), ("tx_status", &["chain", "hash", "evmNetwork"][..]), ("execute_prepared", &["quoteId", "confirmed"][..]), + ("account", &["chain", "accountIndex"][..]), + ("prepare_program", &["accountIndex", "transaction"][..]), + ("execute_prepared_program", &["accountIndex", "quoteId"][..]), ] { let schema = wallet_schemas(function); expect_schema_input_order(&schema, inputs); From 17455dce28ec185ff9cfed1e057c0375a9460ae5 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Sun, 15 Nov 2026 21:50:54 +0000 Subject: [PATCH 13/32] feat(web3): add tests for wallet program instructions Added a test module covering the wallet program's instruction handling to verify the expected behaviour of the on-chain program logic. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../src/web3/wallet/program_tests.rs | 443 ++++++++++++++++++ 1 file changed, 443 insertions(+) create mode 100644 crates/openhuman-core/src/web3/wallet/program_tests.rs diff --git a/crates/openhuman-core/src/web3/wallet/program_tests.rs b/crates/openhuman-core/src/web3/wallet/program_tests.rs new file mode 100644 index 00000000000..6a93da01577 --- /dev/null +++ b/crates/openhuman-core/src/web3/wallet/program_tests.rs @@ -0,0 +1,443 @@ +use super::*; +use crate::config::schema::{WalletAccountPolicy, WalletMintCap}; + +/// `m/44'/501'/1'/0'` of the BIP-39 test phrase (see `ops_tests.rs`). +const SIGNER: &str = "Hh8QwFUA6MtVu1qAoq12ucvFHNwCcVTV7hpWjeY1Hztb"; +const DISTRIBUTOR: &str = "Distributor11111111111111111111111111111111"; +const NOW: u64 = 30 * DAY_MS; + +fn key(text: &str) -> [u8; 32] { + let bytes = bs58::decode(text).into_vec().expect("base58 key"); + <[u8; 32]>::try_from(bytes.as_slice()).expect("32-byte key") +} + +fn filled(byte: u8) -> [u8; 32] { + [byte; 32] +} + +fn mint() -> String { + base58(&filled(7)) +} + +fn other_mint() -> String { + base58(&filled(8)) +} + +fn compact(out: &mut Vec, mut value: usize) { + loop { + let mut byte = (value & 0x7f) as u8; + value >>= 7; + if value != 0 { + byte |= 0x80; + } + out.push(byte); + if value == 0 { + break; + } + } +} + +/// A test instruction: program key and (key, data) with keys added to the +/// message on first use. +struct Ix { + program: [u8; 32], + accounts: Vec<[u8; 32]>, + data: Vec, +} + +/// Serialize an unsigned transaction with `signer` as account 0. +fn build(signer: [u8; 32], required: u8, instructions: &[Ix], v0_lookups: Option) -> Vec { + let mut keys = vec![signer]; + let mut index_of = |key: [u8; 32], keys: &mut Vec<[u8; 32]>| -> u8 { + if let Some(position) = keys.iter().position(|existing| *existing == key) { + return position as u8; + } + keys.push(key); + (keys.len() - 1) as u8 + }; + let compiled: Vec<(u8, Vec, Vec)> = instructions + .iter() + .map(|ix| { + let accounts = ix.accounts.iter().map(|k| index_of(*k, &mut keys)).collect(); + let program = index_of(ix.program, &mut keys); + (program, accounts, ix.data.clone()) + }) + .collect(); + let mut message = Vec::new(); + if v0_lookups.is_some() { + message.push(0x80); + } + message.extend([required, 0, 0]); + compact(&mut message, keys.len()); + for key in &keys { + message.extend(key); + } + message.extend(filled(9)); + compact(&mut message, compiled.len()); + for (program, accounts, data) in &compiled { + message.push(*program); + compact(&mut message, accounts.len()); + message.extend(accounts); + compact(&mut message, data.len()); + message.extend(data); + } + if let Some(count) = v0_lookups { + compact(&mut message, count); + for _ in 0..count { + message.extend(filled(5)); + compact(&mut message, 1); + message.push(0); + compact(&mut message, 0); + } + } + let mut tx = Vec::new(); + compact(&mut tx, usize::from(required)); + tx.extend(std::iter::repeat_n(0u8, 64 * usize::from(required))); + tx.extend(message); + tx +} + +fn transfer_checked(mint: &str, amount: u64) -> Ix { + let mut data = vec![TOKEN_TRANSFER_CHECKED]; + data.extend(amount.to_le_bytes()); + data.push(6); + Ix { + program: key(TOKEN_PROGRAM), + accounts: vec![filled(1), key(mint), filled(2), key(SIGNER)], + data, + } +} + +fn distributor_call() -> Ix { + Ix { + program: key(DISTRIBUTOR), + accounts: vec![filled(3), key(SIGNER)], + data: vec![0xaa, 0xbb], + } +} + +fn ata_create() -> Ix { + Ix { + program: key(ASSOCIATED_TOKEN_PROGRAM), + accounts: vec![key(SIGNER), filled(2), filled(3), key(&mint())], + data: vec![1], + } +} + +fn policy() -> WalletPolicyConfig { + let mut policy = WalletPolicyConfig::default(); + policy.accounts.insert( + "solana_1".into(), + WalletAccountPolicy { + allowed_programs: vec![ + TOKEN_PROGRAM.into(), + ASSOCIATED_TOKEN_PROGRAM.into(), + DISTRIBUTOR.into(), + ], + mints: vec![WalletMintCap { + mint: mint(), + per_tx_max_raw: 1_000, + daily_max_raw: 1_500, + }], + }, + ); + policy +} + +fn summary_of(instructions: &[Ix]) -> ProgramTransactionSummary { + let tx = build(key(SIGNER), 1, instructions, None); + summarize(&decode_transaction(&tx).unwrap(), SIGNER).unwrap() +} + +fn refusal_kind(result: Result<(), PolicyRefusal>) -> RefusalKind { + result.expect_err("expected a refusal").kind +} + +fn spent(amount: u64, at: u64, index: u32, status: LedgerStatus) -> LedgerRecord { + let prepared = PreparedProgram { + quote_id: format!("{QUOTE_PREFIX}old-{at}"), + chain: WalletChain::Solana, + account_index: index, + address: SIGNER.into(), + summary: summary_of(&[transfer_checked(&mint(), amount)]), + created_at_ms: at, + expires_at_ms: at + QUOTE_TTL_MS, + }; + program_record(&prepared, &ExecutionOrigin::rpc(), status, at) +} + +#[test] +fn a_distributor_funding_transaction_decodes_into_its_summary() { + let tx = build( + key(SIGNER), + 1, + &[ata_create(), transfer_checked(&mint(), 600), distributor_call()], + None, + ); + let decoded = decode_transaction(&tx).unwrap(); + assert!(!decoded.versioned); + assert_eq!(decoded.message, tx[65..].to_vec()); + let summary = summarize(&decoded, SIGNER).unwrap(); + assert_eq!(summary.fee_payer, SIGNER); + assert_eq!( + summary.programs, + vec![ + ASSOCIATED_TOKEN_PROGRAM.to_string(), + TOKEN_PROGRAM.to_string(), + DISTRIBUTOR.to_string() + ] + ); + assert_eq!(summary.movements.len(), 1); + assert_eq!(summary.movements[0].mint, mint()); + assert_eq!(summary.movements[0].amount_raw, "600"); + assert_eq!(summary.movements[0].decimals, 6); + assert_eq!(summary.movements[0].authority, SIGNER); + assert_eq!(summary.totals, vec![MintTotal { mint: mint(), amount_raw: "600".into() }]); + assert_eq!(summary.instructions[2].data_hex, "aabb"); + assert_eq!( + evaluate_program(&policy(), "solana", 1, &summary, &[], NOW), + Ok(()) + ); +} + +#[test] +fn a_v0_message_without_lookup_tables_decodes() { + let tx = build(key(SIGNER), 1, &[distributor_call()], Some(0)); + let decoded = decode_transaction(&tx).unwrap(); + assert!(decoded.versioned); + let summary = summarize(&decoded, SIGNER).unwrap(); + assert_eq!(summary.programs, vec![DISTRIBUTOR.to_string()]); + assert!(summary.totals.is_empty()); +} + +#[test] +fn malformed_bytes_are_rejected() { + let tx = build(key(SIGNER), 1, &[distributor_call()], None); + assert!(decode_transaction(&tx[..tx.len() - 1]).is_err()); + let mut trailing = tx.clone(); + trailing.push(0); + assert!(decode_transaction(&trailing).is_err()); + assert!(decode_transaction(&[]).is_err()); + assert!(decode_transaction(&vec![0u8; MAX_TRANSACTION_BYTES + 1]).is_err()); +} + +#[test] +fn an_account_without_a_policy_section_is_refused() { + let summary = summary_of(&[distributor_call()]); + assert_eq!( + refusal_kind(evaluate_program(&WalletPolicyConfig::default(), "solana", 1, &summary, &[], NOW)), + RefusalKind::AccountNotAllowed + ); + // A section for index 1 does not open index 0 or index 2. + for index in [0, 2] { + assert_eq!( + refusal_kind(evaluate_program(&policy(), "solana", index, &summary, &[], NOW)), + RefusalKind::AccountNotAllowed + ); + } +} + +#[test] +fn an_unlisted_program_is_refused() { + let unlisted = Ix { + program: filled(42), + accounts: vec![key(SIGNER)], + data: vec![], + }; + let summary = summary_of(&[distributor_call(), unlisted]); + let refused = evaluate_program(&policy(), "solana", 1, &summary, &[], NOW).unwrap_err(); + assert_eq!(refused.kind, RefusalKind::ProgramNotAllowed); + assert!(refused.message.contains(&base58(&filled(42))), "{}", refused.message); + assert!(refused.to_string().starts_with(super::super::policy::POLICY_REFUSED_PREFIX)); +} + +#[test] +fn a_transfer_over_the_per_transaction_cap_is_refused() { + // Two transfers of 600 total 1200, over the 1000 cap even though each is under. + let summary = summary_of(&[ + transfer_checked(&mint(), 600), + transfer_checked(&mint(), 600), + ]); + assert_eq!(summary.totals[0].amount_raw, "1200"); + assert_eq!( + refusal_kind(evaluate_program(&policy(), "solana", 1, &summary, &[], NOW)), + RefusalKind::PerTransaction + ); + let at_cap = summary_of(&[transfer_checked(&mint(), 1_000)]); + assert_eq!(evaluate_program(&policy(), "solana", 1, &at_cap, &[], NOW), Ok(())); +} + +#[test] +fn the_rolling_day_cap_counts_only_this_accounts_program_records() { + let summary = summary_of(&[transfer_checked(&mint(), 600)]); + let records = vec![ + spent(1_000, NOW - 1_000, 1, LedgerStatus::Broadcast), + // Refused, older than a day, or another account's: not counted. + spent(1_000, NOW - 500, 1, LedgerStatus::Refused), + spent(1_000, NOW - DAY_MS - 1, 1, LedgerStatus::Broadcast), + spent(1_000, NOW - 500, 2, LedgerStatus::Broadcast), + ]; + let refused = evaluate_program(&policy(), "solana", 1, &summary, &records, NOW).unwrap_err(); + assert_eq!(refused.kind, RefusalKind::Daily); + assert!(refused.message.contains("1000 already spent"), "{}", refused.message); + + let small = summary_of(&[transfer_checked(&mint(), 500)]); + assert_eq!(evaluate_program(&policy(), "solana", 1, &small, &records, NOW), Ok(())); + // An in-doubt attempt counts as spent. + let mut in_doubt = records.clone(); + in_doubt.push(spent(1, NOW - 10, 1, LedgerStatus::InDoubt)); + assert_eq!( + refusal_kind(evaluate_program(&policy(), "solana", 1, &small, &in_doubt, NOW)), + RefusalKind::Daily + ); +} + +#[test] +fn an_unlisted_mint_is_refused() { + let summary = summary_of(&[transfer_checked(&other_mint(), 1)]); + assert_eq!( + refusal_kind(evaluate_program(&policy(), "solana", 1, &summary, &[], NOW)), + RefusalKind::MintNotAllowed + ); +} + +#[test] +fn two_mints_in_one_transaction_are_refused() { + let mut policy = policy(); + policy.accounts.get_mut("solana_1").unwrap().mints.push(WalletMintCap { + mint: other_mint(), + per_tx_max_raw: 1_000, + daily_max_raw: 1_000, + }); + let summary = summary_of(&[ + transfer_checked(&mint(), 1), + transfer_checked(&other_mint(), 1), + ]); + assert_eq!( + refusal_kind(evaluate_program(&policy, "solana", 1, &summary, &[], NOW)), + RefusalKind::TransactionNotAllowed + ); +} + +fn summarize_kind(tx: &[u8], signer: &str) -> RefusalKind { + summarize(&decode_transaction(tx).unwrap(), signer) + .expect_err("expected a refusal") + .kind +} + +#[test] +fn a_transaction_another_key_pays_for_or_cosigns_is_refused() { + let tx = build(filled(4), 1, &[distributor_call()], None); + assert_eq!(summarize_kind(&tx, SIGNER), RefusalKind::TransactionNotAllowed); + let cosigned = build(key(SIGNER), 2, &[distributor_call()], None); + assert_eq!(summarize_kind(&cosigned, SIGNER), RefusalKind::TransactionNotAllowed); +} + +#[test] +fn address_lookup_tables_are_refused() { + let tx = build(key(SIGNER), 1, &[distributor_call()], Some(1)); + assert_eq!(summarize_kind(&tx, SIGNER), RefusalKind::TransactionNotAllowed); +} + +#[test] +fn system_and_unaccountable_token_instructions_are_refused_whatever_the_policy() { + let system_transfer = Ix { + program: key(SYSTEM_PROGRAM), + accounts: vec![key(SIGNER), filled(2)], + data: vec![2, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], + }; + let plain_transfer = Ix { + program: key(TOKEN_PROGRAM), + accounts: vec![filled(1), filled(2), key(SIGNER)], + data: [vec![3], 5u64.to_le_bytes().to_vec()].concat(), + }; + let approve = Ix { + program: key(TOKEN_PROGRAM), + accounts: vec![filled(1), filled(2), key(SIGNER)], + data: [vec![4], 5u64.to_le_bytes().to_vec()].concat(), + }; + let set_authority = Ix { + program: key(TOKEN_2022_PROGRAM), + accounts: vec![filled(1), key(SIGNER)], + data: vec![6, 2, 0], + }; + let recover_nested = Ix { + program: key(ASSOCIATED_TOKEN_PROGRAM), + accounts: vec![key(SIGNER)], + data: vec![2], + }; + for ix in [system_transfer, plain_transfer, approve, set_authority, recover_nested] { + let tx = build(key(SIGNER), 1, &[ix], None); + assert_eq!(summarize_kind(&tx, SIGNER), RefusalKind::InstructionNotAllowed); + } +} + +#[test] +fn the_signature_lands_in_slot_zero_and_the_message_is_untouched() { + let tx = build(key(SIGNER), 1, &[distributor_call()], None); + let decoded = decode_transaction(&tx).unwrap(); + let signed = attach_signature(&tx, &decoded, &[0xab; 64]).unwrap(); + assert_eq!(&signed[1..65], &[0xab; 64][..]); + assert_eq!(&signed[65..], decoded.message.as_slice()); + assert_eq!(decode_transaction(&signed).unwrap().message, decoded.message); +} + +#[test] +fn program_records_are_marked_with_their_kind_and_account() { + let record = spent(250, NOW, 1, LedgerStatus::Pending); + assert_eq!(record.kind, LedgerKind::Program); + assert_eq!(record.account_index, 1); + assert_eq!(record.token_address.as_deref(), Some(mint().as_str())); + assert_eq!(record.amount_raw, "250"); + assert_eq!(record.to_address, base58(&filled(2))); + let json = serde_json::to_value(&record).unwrap(); + assert_eq!(json["kind"], "program"); + assert_eq!(json["accountIndex"], 1); +} + +#[test] +fn params_take_camel_or_snake_case_account_index() { + let camel: ExecuteProgramParams = + serde_json::from_value(serde_json::json!({"accountIndex": 1, "quoteId": "q"})).unwrap(); + let snake: ExecuteProgramParams = + serde_json::from_value(serde_json::json!({"account_index": 1, "quoteId": "q"})).unwrap(); + assert_eq!(camel.account_index, 1); + assert_eq!(snake.account_index, 1); +} + +#[tokio::test] +async fn prepare_refuses_an_account_without_a_section_before_touching_the_wallet() { + let temp = tempfile::tempdir().expect("temp dir"); + let _wallet_lock = crate::web3::wallet::test_support::TEST_LOCK.lock().await; + let _workspace = crate::web3::wallet::test_support::set_workspace_env_for_test(&temp).await; + let tx = build(key(SIGNER), 1, &[distributor_call()], None); + let error = prepare_program( + &DispatchCtx::process_default(), + PrepareProgramParams { + account_index: 1, + transaction: base64::engine::general_purpose::STANDARD.encode(tx), + }, + ) + .await + .expect_err("no [wallet_policy.accounts.solana_1] section"); + assert!(error.contains("WALLET_POLICY_REFUSED:"), "{error}"); + assert!(error.contains("solana_1"), "{error}"); +} + +#[tokio::test] +async fn execute_refuses_an_unknown_quote() { + let temp = tempfile::tempdir().expect("temp dir"); + let _wallet_lock = crate::web3::wallet::test_support::TEST_LOCK.lock().await; + let _workspace = crate::web3::wallet::test_support::set_workspace_env_for_test(&temp).await; + let error = execute_prepared_program( + &DispatchCtx::process_default(), + ExecuteProgramParams { + account_index: 1, + quote_id: format!("{QUOTE_PREFIX}missing"), + }, + ) + .await + .expect_err("unknown quote"); + assert!(error.contains("unavailable"), "{error}"); + assert!(!has_quote_for_test("prog-missing")); +} From fbb1e6a631e8ca98d054c974e2d267d338ca1777 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Sun, 15 Nov 2026 21:53:50 +0000 Subject: [PATCH 14/32] test(wallet): cover per-account policy and secondary account derivation Adds tests for parsing and round-tripping per-account wallet policy sections, rejecting malformed mint caps, and omitting an empty accounts map. Also covers Solana index-1 derivation against known vectors, unchanged primary accounts, and legacy stored accounts without an index reading as primary. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../src/config/schema/wallet_policy_tests.rs | 45 +++++ .../src/web3/wallet/ops_tests.rs | 184 ++++++++++++++++++ .../src/web3/wallet/policy_tests.rs | 35 ++++ .../src/web3/wallet/program_tests.rs | 11 +- .../src/web3/wallet/test_support.rs | 2 + 5 files changed, 271 insertions(+), 6 deletions(-) diff --git a/crates/openhuman-core/src/config/schema/wallet_policy_tests.rs b/crates/openhuman-core/src/config/schema/wallet_policy_tests.rs index 71b3f91be1e..c331ca504d7 100644 --- a/crates/openhuman-core/src/config/schema/wallet_policy_tests.rs +++ b/crates/openhuman-core/src/config/schema/wallet_policy_tests.rs @@ -92,3 +92,48 @@ fn a_misspelled_asset_cap_field_is_rejected_instead_of_leaving_the_cap_off() { .unwrap_err(); assert!(error.to_string().contains("daily_max_raww"), "{error}"); } + +#[test] +fn per_account_program_sections_parse_and_round_trip() { + let config: crate::config::schema::Config = toml::from_str( + r#" +[wallet_policy.accounts.solana_1] +allowed_programs = ["TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA"] + +[[wallet_policy.accounts.solana_1.mints]] +mint = "Mint1111111111111111111111111111111111111111" +per_tx_max_raw = 1000 +daily_max_raw = 2000 +"#, + ) + .unwrap(); + let policy = config.wallet_policy; + assert!(policy.assets.is_empty()); + let section = policy.account_policy("solana", 1).expect("section"); + assert_eq!(section.allowed_programs.len(), 1); + assert_eq!(section.mints[0].per_tx_max_raw, 1000); + assert_eq!(section.mints[0].daily_max_raw, 2000); + assert!(policy.account_policy("solana", 0).is_none()); + assert_eq!(WalletPolicyConfig::account_key("Solana", 1), "solana_1"); + + let text = toml::to_string(&policy).unwrap(); + let back: WalletPolicyConfig = toml::from_str(&text).unwrap(); + assert_eq!(back, policy); +} + +#[test] +fn an_empty_accounts_map_is_not_serialized() { + let text = toml::to_string(&WalletPolicyConfig::default()).unwrap(); + assert!(!text.contains("accounts"), "{text}"); +} + +#[test] +fn a_mint_cap_without_both_caps_or_with_a_typo_fails_to_parse() { + for body in [ + "mint = \"m\"\nper_tx_max_raw = 1\n", + "mint = \"m\"\nper_tx_max_raw = 1\ndaily_max_raw = 1\ndaily_max_raww = 1\n", + ] { + let text = format!("[[wallet_policy.accounts.solana_1.mints]]\n{body}"); + assert!(toml::from_str::(&text).is_err(), "{body}"); + } +} diff --git a/crates/openhuman-core/src/web3/wallet/ops_tests.rs b/crates/openhuman-core/src/web3/wallet/ops_tests.rs index 78ea6219ed9..0f028f70921 100644 --- a/crates/openhuman-core/src/web3/wallet/ops_tests.rs +++ b/crates/openhuman-core/src/web3/wallet/ops_tests.rs @@ -7,6 +7,18 @@ fn sample_account(chain: WalletChain) -> WalletAccount { chain, address: format!("addr-{}", chain.as_str()), derivation_path: format!("m/44'/0'/0'/0/{}", chain.as_str()), + index: 0, + label: None, + } +} + +fn giveaway_account() -> WalletAccount { + WalletAccount { + chain: WalletChain::Solana, + address: "addr-solana-1".to_string(), + derivation_path: "m/44'/501'/1'/0'".to_string(), + index: 1, + label: Some("giveaway".to_string()), } } @@ -251,3 +263,175 @@ async fn reveal_recovery_phrase_returns_phrase_for_existing_wallet() { ); assert_eq!(result.value.word_count, 12); } + +// ── Secondary accounts ─────────────────────────────────────────────────── + +/// The expected addresses were computed independently of TinyWallet: a +/// standalone SLIP-0010 ed25519 derivation (Python `hashlib` PBKDF2/HMAC-SHA512 +/// plus `cryptography`'s Ed25519) of the BIP-39 test phrase +/// "abandon × 11 about". Its index-0 result matches the published Solana +/// vector `HAgk14JpMQLgt6rVgv7cBQFJWFto5Dqxi472uT3DKpqk` (what Phantom and +/// `solana-keygen` derive at `m/44'/501'/0'/0'`), which is what makes it a +/// trustworthy oracle for index 1 (`m/44'/501'/1'/0'`, Phantom's "Account 2"). +const SOLANA_INDEX_0_VECTOR: &str = "HAgk14JpMQLgt6rVgv7cBQFJWFto5Dqxi472uT3DKpqk"; +const SOLANA_INDEX_1_VECTOR: &str = "Hh8QwFUA6MtVu1qAoq12ucvFHNwCcVTV7hpWjeY1Hztb"; + +fn derive_solana(path: &str) -> String { + tinywallet::key::derive( + tinywallet::Chain::Solana, + crate::web3::wallet::test_support::TEST_MNEMONIC, + path, + ) + .expect("derive") + .address() + .to_string() +} + +#[test] +fn solana_index_one_derives_the_known_vector_address() { + let path = account_derivation_path(WalletChain::Solana, 1).expect("index 1 is known"); + assert_eq!(path, "m/44'/501'/1'/0'"); + assert_eq!(derive_solana(path), SOLANA_INDEX_1_VECTOR); +} + +#[test] +fn primary_accounts_are_unchanged() { + assert_eq!( + account_derivation_path(WalletChain::Solana, 0), + Some("m/44'/501'/0'/0'") + ); + assert_eq!(derive_solana("m/44'/501'/0'/0'"), SOLANA_INDEX_0_VECTOR); + let plan = derivation_plan(); + let primary: Vec<_> = plan + .iter() + .take(4) + .map(|account| (account.chain, account.derivation_path.as_str(), account.index)) + .collect(); + assert_eq!( + primary, + vec![ + (WalletChain::Evm, "m/44'/60'/0'/0/0", 0), + (WalletChain::Btc, "m/44'/0'/0'/0/0", 0), + (WalletChain::Solana, "m/44'/501'/0'/0'", 0), + (WalletChain::Tron, "m/44'/195'/0'/0/0", 0), + ] + ); + assert!(plan.iter().take(4).all(|account| account.label.is_none())); + // Recovery and import also derive the giveaway account, after the four. + assert_eq!(plan.len(), 5); + assert_eq!(plan[4].chain, WalletChain::Solana); + assert_eq!(plan[4].index, 1); + assert_eq!(plan[4].derivation_path, "m/44'/501'/1'/0'"); + assert_eq!(plan[4].label.as_deref(), Some("giveaway")); + // Only Solana has a secondary account. + assert_eq!(account_derivation_path(WalletChain::Evm, 1), None); + assert_eq!(account_derivation_path(WalletChain::Solana, 2), None); +} + +#[test] +fn stored_accounts_without_an_index_read_as_primary_and_serialize_unchanged() { + let legacy = serde_json::json!({ + "chain": "solana", + "address": "addr", + "derivationPath": "m/44'/501'/0'/0'" + }); + let account: WalletAccount = serde_json::from_value(legacy.clone()).unwrap(); + assert_eq!(account.index, 0); + assert!(account.is_primary()); + assert_eq!(serde_json::to_value(&account).unwrap(), legacy); + let secondary = serde_json::to_value(giveaway_account()).unwrap(); + assert_eq!(secondary["index"], 1); + assert_eq!(secondary["label"], "giveaway"); +} + +#[test] +fn validate_setup_accepts_the_giveaway_account_beside_the_four() { + let mut params = sample_params(); + params.accounts.push(giveaway_account()); + let accounts = validate_setup(¶ms).expect("valid wallet setup"); + assert_eq!(accounts.len(), 5); + assert_eq!(accounts[4].index, 1); +} + +#[test] +fn validate_setup_rejects_unknown_or_duplicate_secondary_accounts() { + let mut params = sample_params(); + let mut wrong_path = giveaway_account(); + wrong_path.derivation_path = "m/44'/501'/7'/0'".to_string(); + params.accounts.push(wrong_path); + assert!(validate_setup(¶ms) + .expect_err("non-canonical path") + .contains("not a known secondary account")); + + let mut params = sample_params(); + let mut unknown = giveaway_account(); + unknown.chain = WalletChain::Evm; + params.accounts.push(unknown); + assert!(validate_setup(¶ms).is_err()); + + let mut params = sample_params(); + params.accounts.push(giveaway_account()); + params.accounts.push(giveaway_account()); + assert!(validate_setup(¶ms) + .expect_err("duplicate") + .contains("more than once")); + + // A secondary account never stands in for a missing primary one. + let mut params = sample_params(); + params.accounts.retain(|account| account.chain != WalletChain::Solana); + params.accounts.push(giveaway_account()); + assert!(validate_setup(¶ms) + .expect_err("no primary solana") + .contains("exactly one 'solana'")); +} + +#[test] +fn status_keeps_secondary_accounts_out_of_the_primary_list() { + let config = Config::default(); + let mut state = stored_state(); + state.accounts.push(giveaway_account()); + let status = to_status(&config, Some(state)); + assert_eq!(status.accounts.len(), 4); + assert!(status.accounts.iter().all(WalletAccount::is_primary)); + assert_eq!(status.additional_accounts, vec![giveaway_account()]); + let json = serde_json::to_value(&status).unwrap(); + assert_eq!(json["additionalAccounts"][0]["label"], "giveaway"); + + let plain = to_status(&config, Some(stored_state())); + let json = serde_json::to_value(&plain).unwrap(); + assert!(json.get("additionalAccounts").is_none()); +} + +#[tokio::test] +async fn secret_material_resolves_the_secondary_path_for_a_wallet_that_predates_it() { + let temp = tempfile::tempdir().expect("temp dir"); + let _wallet_lock = crate::web3::wallet::test_support::TEST_LOCK.lock().await; + let ctx = DispatchCtx::process_default(); + let _workspace = crate::web3::wallet::test_support::setup_wallet_in(&ctx, &temp) + .await + .expect("setup wallet"); + let primary = secret_material(&ctx, WalletChain::Solana, 0) + .await + .expect("primary"); + assert_eq!(primary.derivation_path, "m/44'/501'/0'/0'"); + let giveaway = secret_material(&ctx, WalletChain::Solana, 1) + .await + .expect("secondary resolves without being stored"); + assert_eq!(giveaway.derivation_path, "m/44'/501'/1'/0'"); + assert_eq!(giveaway.encrypted_mnemonic, primary.encrypted_mnemonic); + let error = secret_material(&ctx, WalletChain::Solana, 2) + .await + .expect_err("index 2 is unknown"); + assert!(error.contains("index 2"), "{error}"); + let error = ensure_account(&ctx, WalletChain::Evm, 1) + .await + .expect_err("evm has no secondary account"); + assert!(error.contains("secondary accounts are"), "{error}"); + let stored = ensure_account(&ctx, WalletChain::Solana, 0) + .await + .expect("the primary account is stored"); + assert_eq!( + stored.address, + crate::web3::wallet::test_support::sample_solana_address() + ); +} diff --git a/crates/openhuman-core/src/web3/wallet/policy_tests.rs b/crates/openhuman-core/src/web3/wallet/policy_tests.rs index 5ddb0b2bc60..d40938be3ce 100644 --- a/crates/openhuman-core/src/web3/wallet/policy_tests.rs +++ b/crates/openhuman-core/src/web3/wallet/policy_tests.rs @@ -465,3 +465,38 @@ fn a_plain_cron_turn_is_refused_by_the_spend_policy() { RefusalKind::Origin ); } + +#[test] +fn program_records_never_count_against_the_primary_accounts_caps() { + // A program execute of the same mint and amount, from either account, + // leaves the index-0 transfer caps exactly as they were. + let mut program = spent(100_000_000, NOW - 1_000, LedgerStatus::Broadcast); + program.kind = LedgerKind::Program; + let mut secondary = program.clone(); + secondary.account_index = 1; + let q = quote("q", "USDC", 50_000_000, RECIPIENT); + assert_eq!( + evaluate(&policy(), &automation(), &q, &[program, secondary], NOW), + Ok(true) + ); + // The same record as a transfer is counted, as before. + let transfer = spent(100_000_000, NOW - 1_000, LedgerStatus::Broadcast); + assert_eq!( + kind(evaluate(&policy(), &automation(), &q, &[transfer], NOW)), + RefusalKind::Daily + ); +} + +#[test] +fn an_account_section_does_not_change_the_primary_asset_policy() { + let mut with_section = policy(); + with_section.accounts.insert( + "solana_1".into(), + crate::config::schema::WalletAccountPolicy::default(), + ); + let q = quote("q", "USDC", 60_000_000, RECIPIENT); + assert_eq!( + evaluate(&with_section, &automation(), &q, &[], NOW), + evaluate(&policy(), &automation(), &q, &[], NOW) + ); +} diff --git a/crates/openhuman-core/src/web3/wallet/program_tests.rs b/crates/openhuman-core/src/web3/wallet/program_tests.rs index 6a93da01577..d3212499e8d 100644 --- a/crates/openhuman-core/src/web3/wallet/program_tests.rs +++ b/crates/openhuman-core/src/web3/wallet/program_tests.rs @@ -3,7 +3,6 @@ use crate::config::schema::{WalletAccountPolicy, WalletMintCap}; /// `m/44'/501'/1'/0'` of the BIP-39 test phrase (see `ops_tests.rs`). const SIGNER: &str = "Hh8QwFUA6MtVu1qAoq12ucvFHNwCcVTV7hpWjeY1Hztb"; -const DISTRIBUTOR: &str = "Distributor11111111111111111111111111111111"; const NOW: u64 = 30 * DAY_MS; fn key(text: &str) -> [u8; 32] { @@ -48,7 +47,7 @@ struct Ix { /// Serialize an unsigned transaction with `signer` as account 0. fn build(signer: [u8; 32], required: u8, instructions: &[Ix], v0_lookups: Option) -> Vec { let mut keys = vec![signer]; - let mut index_of = |key: [u8; 32], keys: &mut Vec<[u8; 32]>| -> u8 { + let index_of = |key: [u8; 32], keys: &mut Vec<[u8; 32]>| -> u8 { if let Some(position) = keys.iter().position(|existing| *existing == key) { return position as u8; } @@ -110,7 +109,7 @@ fn transfer_checked(mint: &str, amount: u64) -> Ix { fn distributor_call() -> Ix { Ix { - program: key(DISTRIBUTOR), + program: filled(11), accounts: vec![filled(3), key(SIGNER)], data: vec![0xaa, 0xbb], } @@ -132,7 +131,7 @@ fn policy() -> WalletPolicyConfig { allowed_programs: vec![ TOKEN_PROGRAM.into(), ASSOCIATED_TOKEN_PROGRAM.into(), - DISTRIBUTOR.into(), + base58(&filled(11)), ], mints: vec![WalletMintCap { mint: mint(), @@ -184,7 +183,7 @@ fn a_distributor_funding_transaction_decodes_into_its_summary() { vec![ ASSOCIATED_TOKEN_PROGRAM.to_string(), TOKEN_PROGRAM.to_string(), - DISTRIBUTOR.to_string() + base58(&filled(11)) ] ); assert_eq!(summary.movements.len(), 1); @@ -206,7 +205,7 @@ fn a_v0_message_without_lookup_tables_decodes() { let decoded = decode_transaction(&tx).unwrap(); assert!(decoded.versioned); let summary = summarize(&decoded, SIGNER).unwrap(); - assert_eq!(summary.programs, vec![DISTRIBUTOR.to_string()]); + assert_eq!(summary.programs, vec![base58(&filled(11))]); assert!(summary.totals.is_empty()); } diff --git a/crates/openhuman-core/src/web3/wallet/test_support.rs b/crates/openhuman-core/src/web3/wallet/test_support.rs index 5ae25366be4..aab6c9627e7 100644 --- a/crates/openhuman-core/src/web3/wallet/test_support.rs +++ b/crates/openhuman-core/src/web3/wallet/test_support.rs @@ -49,6 +49,8 @@ pub(crate) fn sample_account(chain: WalletChain) -> WalletAccount { WalletChain::Solana => "m/44'/501'/0'/0'".to_string(), WalletChain::Tron => "m/44'/195'/0'/0/0".to_string(), }, + index: 0, + label: None, } } From 446a13f5ac95a1058cf1289692348ff60a574636 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Sun, 15 Nov 2026 21:56:21 +0000 Subject: [PATCH 15/32] test(wallet): pass recipient to spent helper in policy tests Update the program and transfer ledger fixtures to use the new spent signature that takes a recipient, keeping the spend policy tests compiling against the changed helper. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- crates/openhuman-core/src/web3/wallet/policy_tests.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/openhuman-core/src/web3/wallet/policy_tests.rs b/crates/openhuman-core/src/web3/wallet/policy_tests.rs index d40938be3ce..7176b33786e 100644 --- a/crates/openhuman-core/src/web3/wallet/policy_tests.rs +++ b/crates/openhuman-core/src/web3/wallet/policy_tests.rs @@ -470,7 +470,7 @@ fn a_plain_cron_turn_is_refused_by_the_spend_policy() { fn program_records_never_count_against_the_primary_accounts_caps() { // A program execute of the same mint and amount, from either account, // leaves the index-0 transfer caps exactly as they were. - let mut program = spent(100_000_000, NOW - 1_000, LedgerStatus::Broadcast); + let mut program = spent(100_000_000, RECIPIENT, NOW - 1_000, LedgerStatus::Broadcast); program.kind = LedgerKind::Program; let mut secondary = program.clone(); secondary.account_index = 1; @@ -480,7 +480,7 @@ fn program_records_never_count_against_the_primary_accounts_caps() { Ok(true) ); // The same record as a transfer is counted, as before. - let transfer = spent(100_000_000, NOW - 1_000, LedgerStatus::Broadcast); + let transfer = spent(100_000_000, RECIPIENT, NOW - 1_000, LedgerStatus::Broadcast); assert_eq!( kind(evaluate(&policy(), &automation(), &q, &[transfer], NOW)), RefusalKind::Daily From 2732a7774326b02a17f8d580e0c4a9095e4f40e6 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Sun, 15 Nov 2026 21:59:18 +0000 Subject: [PATCH 16/32] test(wallet): seed legacy wallet state directly in secondary path test Replace the shared wallet setup helper with explicit workspace setup and a hand-written pre-secondary-accounts state so the test exercises the legacy on-disk shape without relying on the helper's current defaults. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../openhuman-core/src/web3/wallet/ops_tests.rs | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/crates/openhuman-core/src/web3/wallet/ops_tests.rs b/crates/openhuman-core/src/web3/wallet/ops_tests.rs index 0f028f70921..6a6d9f75774 100644 --- a/crates/openhuman-core/src/web3/wallet/ops_tests.rs +++ b/crates/openhuman-core/src/web3/wallet/ops_tests.rs @@ -407,9 +407,19 @@ async fn secret_material_resolves_the_secondary_path_for_a_wallet_that_predates_ let temp = tempfile::tempdir().expect("temp dir"); let _wallet_lock = crate::web3::wallet::test_support::TEST_LOCK.lock().await; let ctx = DispatchCtx::process_default(); - let _workspace = crate::web3::wallet::test_support::setup_wallet_in(&ctx, &temp) - .await - .expect("setup wallet"); + let _workspace = crate::web3::wallet::test_support::set_workspace_env_for_test(&temp).await; + let config = ctx.load_config().await.expect("config"); + { + // State as written before secondary accounts existed: four primary + // accounts, no index fields. Nothing here needs the phrase decrypted. + let mut state = stored_state(); + state.accounts = WalletChain::ALL + .into_iter() + .map(crate::web3::wallet::test_support::sample_account) + .collect(); + let _guard = WALLET_STATE_FILE_LOCK.lock(); + save_stored_wallet_state_unlocked(&config, &state).expect("save state"); + } let primary = secret_material(&ctx, WalletChain::Solana, 0) .await .expect("primary"); From cc93f0d66221a80e676c8d94aa5ca6b2cded3f2c Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Sun, 15 Nov 2026 21:59:42 +0000 Subject: [PATCH 17/32] feat(wallet): add secondary Solana account and program transaction signing Adds a second Solana account (index 1, labelled giveaway) derived from the same recovery phrase, exposed through a new wallet.account RPC and reported under additionalAccounts so existing callers still see one account per chain. The new prepare_program and execute_prepared_program methods let that account sign host-built Solana transactions under its own per-account spend policy, and the wallet docs and capability catalog are updated to describe the new flow. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- app/src/services/walletApi.ts | 6 ++++ .../about_app/catalog_workflows_automation.rs | 4 +-- .../openhuman-core/src/web3/wallet/README.md | 28 +++++++++++++++++++ docs/gitbooks/en/features/wallet.md | 22 +++++++++++++++ 4 files changed, 58 insertions(+), 2 deletions(-) diff --git a/app/src/services/walletApi.ts b/app/src/services/walletApi.ts index ce559d568b2..7aae062afc4 100644 --- a/app/src/services/walletApi.ts +++ b/app/src/services/walletApi.ts @@ -27,6 +27,10 @@ export interface WalletAccount { chain: WalletChain; address: string; derivationPath: string; + /** Account index on the chain; absent for the primary (index 0) account. */ + index?: number; + /** Label of a secondary account (`giveaway`). */ + label?: string; } export interface WalletRecoveryMaterial { @@ -48,6 +52,8 @@ export interface WalletStatus { source: WalletSetupSource | null; mnemonicWordCount: number | null; accounts: WalletAccount[]; + /** Secondary accounts (index 1 and up), absent when there are none. */ + additionalAccounts?: WalletAccount[]; updatedAtMs: number | null; } diff --git a/crates/openhuman-core/src/platform/about_app/catalog_workflows_automation.rs b/crates/openhuman-core/src/platform/about_app/catalog_workflows_automation.rs index 606d4db3fb3..f660118594d 100644 --- a/crates/openhuman-core/src/platform/about_app/catalog_workflows_automation.rs +++ b/crates/openhuman-core/src/platform/about_app/catalog_workflows_automation.rs @@ -187,8 +187,8 @@ Capability { name: "Wallet Execution Tools", domain: "wallet", category: CapabilityCategory::Workflows, - description: "Read addresses, native balances and token balances (USDC on Solana, via wallet.token_balances), prepare/confirm/execute native + token transfers (ERC20/SPL/TRC20/BEP20), and inspect transactions (status, receipt, lookup) across the connected wallet (EVM, BTC, Solana, Tron). Quote-first; signing stays local. Agent and automated executes run inside the [wallet_policy] spend policy (asset allowlist, per-transaction, rolling-day and per-recipient weekly caps) and are recorded in a persistent ledger. Switched off by [components] wallet = false, which answers COMPONENT_DISABLED:wallet and leaves keychain material, spending limits and RPC endpoints untouched.", - how_to: "Use wallet.* RPC methods (balances, token_balances, prepare_transfer, execute_prepared, tx_status, tx_receipt, lookup_tx, policy_get, policy_update, ledger_list) via the agent or core_rpc_relay. Settings > Crypto > Wallet Balances shows native balances only; token balances come from wallet.token_balances or the agent's wallet_balances tool.", + description: "Read addresses, native balances and token balances (USDC on Solana, via wallet.token_balances), prepare/confirm/execute native + token transfers (ERC20/SPL/TRC20/BEP20), and inspect transactions (status, receipt, lookup) across the connected wallet (EVM, BTC, Solana, Tron). Quote-first; signing stays local. Agent and automated executes run inside the [wallet_policy] spend policy (asset allowlist, per-transaction, rolling-day and per-recipient weekly caps) and are recorded in a persistent ledger. A secondary Solana account (index 1) can sign host-built program transactions only, under its own [wallet_policy.accounts.solana_1] program and mint allowlist with per-transaction and rolling-day caps. Switched off by [components] wallet = false, which answers COMPONENT_DISABLED:wallet and leaves keychain material, spending limits and RPC endpoints untouched.", + how_to: "Use wallet.* RPC methods (balances, token_balances, prepare_transfer, execute_prepared, tx_status, tx_receipt, lookup_tx, policy_get, policy_update, ledger_list, account, prepare_program, execute_prepared_program) via the agent or core_rpc_relay. Settings > Crypto > Wallet Balances shows native balances only; token balances come from wallet.token_balances or the agent's wallet_balances tool.", status: CapabilityStatus::Beta, privacy: LOCAL_CREDENTIALS, }, diff --git a/crates/openhuman-core/src/web3/wallet/README.md b/crates/openhuman-core/src/web3/wallet/README.md index 17ad36050ad..895c7b6f1f9 100644 --- a/crates/openhuman-core/src/web3/wallet/README.md +++ b/crates/openhuman-core/src/web3/wallet/README.md @@ -47,6 +47,8 @@ changing the facade. | `prepare_transfer`, `execute_prepared` | Prepare a module-owned quote, then explicitly confirm and execute it (through the spend policy, as an interactive execute). | | `policy_get`, `policy_update` | Read and persist the `[wallet_policy]` spend policy. | | `ledger_list` | Recent execute records from the persistent spend ledger (`{limit}`, default 50, max 500). | +| `account` | One account by `{chain, accountIndex}`; derives and stores a known secondary account (Solana index 1, `giveaway`) that the stored state predates. | +| `prepare_program`, `execute_prepared_program` | Check a host-built unsigned Solana transaction against `[wallet_policy.accounts.solana_]`, then sign it in the module with that account's key and send it (`program.rs`). | | `tx_status`, `tx_receipt`, `lookup_tx` | Read transaction lifecycle and raw transaction data through the module. | The four chain families are EVM, Bitcoin, Solana, and Tron. EVM network @@ -95,6 +97,32 @@ harness gate and is refused by the policy; a cron job whose agent opted into sub-agents stay read-only). x402 payments from the same origin are approved within the per-request budget. +## Secondary accounts and program transactions + +Each chain has one primary account (index 0), the only one the module's +transfers, swaps and x402 payments use. `ops::SECONDARY_ACCOUNTS` lists the +extra accounts derived from the same phrase: today Solana index 1 at +`m/44'/501'/1'/0'`, labelled `giveaway`. Recovery derives it with the others; +`setup` stores it; `status` reports it under `additionalAccounts` so callers +that expect one account per chain (and the module's `WalletAccounts` +callback) see only the primaries. A wallet set up before an entry existed +signs with its canonical path anyway, and `ensure_account` (`wallet.account`) +derives and stores its address on first use. + +`program.rs` lets such an account sign a transaction the caller built, +under its own `[wallet_policy.accounts._]` section +(`allowed_programs`, `mints` with `per_tx_max_raw` and `daily_max_raw`). The +host decodes the transaction and refuses it unless the account is the fee +payer and sole signer, every program is listed, token instructions are +`TransferChecked` of one listed mint within its caps, ATA instructions are +creates, and there is no System instruction or lookup table. The quote holds +the exact bytes for 60 seconds; execute re-checks and reserves in the ledger +(`kind = program`, `accountIndex`), signs the message bytes with a +confidential `SignMessage`, and sends the transaction to the Solana RPC (the +host override, else the module's default for the cluster). Program records +never count against the primary account's caps, and transfer records never +count against a program account's. + ## Persistence and lifecycle - `{workspace_dir}/state/wallet-state.json` stores consent and public setup diff --git a/docs/gitbooks/en/features/wallet.md b/docs/gitbooks/en/features/wallet.md index 0375ccaf074..7d62e41f8e7 100644 --- a/docs/gitbooks/en/features/wallet.md +++ b/docs/gitbooks/en/features/wallet.md @@ -127,6 +127,28 @@ The caps of one asset are counted separately from the other's. `OPENHUMAN_WALLET Every execute is written to a ledger before it is signed and updated afterwards. A failed execute is marked *in doubt*: it still counts against the caps and is never retried, so check its status before preparing a new transfer. Scheduled (cron) agent turns are read-only and cannot pay. x402 payments from automation are limited by the x402 budget instead. +### Secondary accounts and program transactions + +Besides the one account per chain, the same recovery phrase gives a second Solana account at `m/44'/501'/1'/0'` (index 1, labelled `giveaway`). New and imported wallets derive it at setup; a wallet set up earlier derives it the first time `wallet.account` asks for it. It is listed under `additionalAccounts` in `wallet.status`, never moves funds through transfers, and is not covered by `[wallet_policy.assets]`. + +It can sign one thing: a Solana transaction another program built, through `wallet.prepare_program` and then `wallet.execute_prepared_program`. Each account that may do this needs its own section, and an account without one is refused: + +```toml +[wallet_policy.accounts.solana_1] +allowed_programs = [ + "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA", # SPL Token + "ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL", # Associated Token Account + "", +] + +[[wallet_policy.accounts.solana_1.mints]] +mint = "" +per_tx_max_raw = 1000000000 +daily_max_raw = 2000000000 +``` + +The transaction is refused if it calls a program not on the list, moves a mint not on the list, moves more than either cap, or needs any signer besides the account. Token movements must be `TransferChecked` instructions, and System program instructions are not signed this way. Executes are written to the same ledger, but they are counted separately from the primary account's caps. + ## See also - [Approval gate](approval-gate.md) From 16730b807b08c62710944b63598cc328a9b9398a Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Sun, 15 Nov 2026 22:00:01 +0000 Subject: [PATCH 18/32] refactor(wallet): split program transaction module into submodules The monolithic program transaction module was broken into a program directory with separate mod and ops files, and its tests moved alongside it. The code is unchanged; the split just makes the prepare and execute paths easier to navigate. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../wallet/{program.rs => program/mod.rs} | 387 +---------------- .../mod_tests.rs} | 0 .../src/web3/wallet/program/ops.rs | 404 ++++++++++++++++++ 3 files changed, 411 insertions(+), 380 deletions(-) rename crates/openhuman-core/src/web3/wallet/{program.rs => program/mod.rs} (59%) rename crates/openhuman-core/src/web3/wallet/{program_tests.rs => program/mod_tests.rs} (100%) create mode 100644 crates/openhuman-core/src/web3/wallet/program/ops.rs diff --git a/crates/openhuman-core/src/web3/wallet/program.rs b/crates/openhuman-core/src/web3/wallet/program/mod.rs similarity index 59% rename from crates/openhuman-core/src/web3/wallet/program.rs rename to crates/openhuman-core/src/web3/wallet/program/mod.rs index 0a711f743c5..97695e03734 100644 --- a/crates/openhuman-core/src/web3/wallet/program.rs +++ b/crates/openhuman-core/src/web3/wallet/program/mod.rs @@ -546,387 +546,14 @@ pub fn evaluate_program( Ok(()) } -// ── Quotes ────────────────────────────────────────────────────────────────── - -/// A prepared program transaction, as returned to the caller. -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct PreparedProgram { - pub quote_id: String, - pub chain: WalletChain, - pub account_index: u32, - /// The signing account's address (the fee payer). - pub address: String, - pub summary: ProgramTransactionSummary, - pub created_at_ms: u64, - pub expires_at_ms: u64, -} - -/// The result of executing a prepared program transaction. -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct ExecutedProgram { - pub quote_id: String, - pub chain: WalletChain, - pub account_index: u32, - pub address: String, - /// The transaction signature (base58), as the RPC accepted it. - pub transaction_hash: String, -} - -/// `wallet.prepare_program` parameters. -#[derive(Debug, Clone, Deserialize)] -#[serde(rename_all = "camelCase", deny_unknown_fields)] -pub struct PrepareProgramParams { - #[serde(alias = "account_index")] - pub account_index: u32, - /// Base64 of the unsigned transaction's wire bytes (signature slots - /// zeroed), e.g. `transaction.serialize({requireAllSignatures: false})`. - pub transaction: String, -} - -/// `wallet.execute_prepared_program` parameters. -#[derive(Debug, Clone, Deserialize)] -#[serde(rename_all = "camelCase", deny_unknown_fields)] -pub struct ExecuteProgramParams { - #[serde(alias = "account_index")] - pub account_index: u32, - #[serde(alias = "quote_id")] - pub quote_id: String, -} - -#[derive(Clone)] -struct StoredQuote { - prepared: PreparedProgram, - transaction: Vec, - decoded: DecodedTransaction, -} - -static QUOTES: Lazy>> = Lazy::new(|| Mutex::new(HashMap::new())); - -fn store_quote(quote: StoredQuote, now_ms: u64) { - if let Ok(mut quotes) = QUOTES.lock() { - quotes.retain(|_, stored| stored.prepared.expires_at_ms > now_ms); - quotes.insert(quote.prepared.quote_id.clone(), quote); - } -} - -fn take_quote(quote_id: &str) -> Option { - QUOTES.lock().ok()?.remove(quote_id) -} - -/// Prepare quotes currently held (test support). +mod ops; +pub use ops::{ + execute_prepared_program, prepare_program, ExecuteProgramParams, ExecutedProgram, + PrepareProgramParams, PreparedProgram, +}; #[cfg(test)] -pub(crate) fn has_quote_for_test(quote_id: &str) -> bool { - QUOTES - .lock() - .is_ok_and(|quotes| quotes.contains_key(quote_id)) -} - -fn chain_name(chain: WalletChain) -> &'static str { - chain.as_str() -} - -fn ledger_records(config: &crate::config::Config) -> Result<(SpendLedger, Vec), String> { - let ledger = SpendLedger::open(&config.workspace_dir) - .map_err(|error| format!("wallet spend ledger is unavailable: {error:#}"))?; - let records = ledger - .records() - .map_err(|error| format!("wallet spend ledger is unavailable: {error:#}"))?; - Ok((ledger, records)) -} - -/// Decode, summarise and check one transaction, then store it as a quote. -/// The policy section is checked before any key derivation. -/// -/// # Errors -/// -/// A policy refusal (prefixed `WALLET_POLICY_REFUSED:`), malformed input, or -/// a wallet that cannot provide the account. -pub async fn prepare_program( - ctx: &DispatchCtx, - params: PrepareProgramParams, -) -> Result, String> { - let chain = WalletChain::Solana; - let config = ctx.load_config().await?; - let key = WalletPolicyConfig::account_key(chain_name(chain), params.account_index); - if config - .wallet_policy - .account_policy(chain_name(chain), params.account_index) - .is_none() - { - return Err(refusal( - RefusalKind::AccountNotAllowed, - format!("account {key} has no [wallet_policy.accounts.{key}] section"), - ) - .to_string()); - } - let transaction = base64::engine::general_purpose::STANDARD - .decode(params.transaction.trim()) - .map_err(|error| format!("transaction is not valid base64: {error}"))?; - let decoded = decode_transaction(&transaction)?; - let account = super::ops::ensure_account(ctx, chain, params.account_index).await?; - let summary = summarize(&decoded, &account.address).map_err(|refused| refused.to_string())?; - let now = super::policy::wall_clock_ms(); - let (_, records) = ledger_records(&config)?; - evaluate_program( - &config.wallet_policy, - chain_name(chain), - params.account_index, - &summary, - &records, - now, - ) - .map_err(|refused| { - tracing::info!(account = %key, kind = ?refused.kind, "{LOG_PREFIX} prepare refused"); - refused.to_string() - })?; - let prepared = PreparedProgram { - quote_id: format!("{QUOTE_PREFIX}{}", uuid::Uuid::new_v4()), - chain, - account_index: params.account_index, - address: account.address, - summary, - created_at_ms: now, - expires_at_ms: now + QUOTE_TTL_MS, - }; - tracing::info!( - quote_id = %prepared.quote_id, - account = %key, - programs = prepared.summary.programs.len(), - movements = prepared.summary.movements.len(), - "{LOG_PREFIX} prepared" - ); - store_quote( - StoredQuote { - prepared: prepared.clone(), - transaction, - decoded, - }, - now, - ); - Ok(Outcome::new( - prepared, - vec!["wallet program transaction prepared".to_string()], - )) -} - -/// The ledger record of one program execute. -fn program_record( - prepared: &PreparedProgram, - origin: &ExecutionOrigin, - status: LedgerStatus, - now_ms: u64, -) -> LedgerRecord { - let total = prepared.summary.totals.first(); - let destination = match prepared.summary.movements.as_slice() { - [] => String::new(), - [only] => only.destination.clone(), - [first, rest @ ..] if rest.iter().all(|m| m.destination == first.destination) => { - first.destination.clone() - } - _ => "multiple".to_string(), - }; - LedgerRecord { - id: uuid::Uuid::new_v4().to_string(), - quote_id: prepared.quote_id.clone(), - created_at_ms: now_ms, - updated_at_ms: now_ms, - origin: origin.label().into(), - origin_class: origin.class().into(), - policy_applied: true, - chain: chain_name(prepared.chain).to_string(), - evm_network: None, - asset_symbol: if total.is_some() { "SPL" } else { "" }.to_string(), - token_address: total.map(|total| total.mint.clone()), - to_address: destination, - amount_raw: total.map_or_else(|| "0".to_string(), |total| total.amount_raw.clone()), - status, - transaction_hash: None, - error: None, - kind: LedgerKind::Program, - account_index: prepared.account_index, - } -} - -/// Execute a prepared program transaction: re-check and reserve under the -/// policy, sign in the module, send. A quote is single-use once an attempt -/// reached signing. -/// -/// # Errors -/// -/// A policy refusal (prefixed `WALLET_POLICY_REFUSED:`), an unknown or -/// expired quote, or the signing or send error (the attempt is then recorded -/// `in_doubt` and never retried). -pub async fn execute_prepared_program( - ctx: &DispatchCtx, - params: ExecuteProgramParams, -) -> Result, String> { - let config = ctx.load_config().await?; - let now = super::policy::wall_clock_ms(); - let stored = take_quote(¶ms.quote_id) - .filter(|stored| stored.prepared.expires_at_ms > now) - .ok_or_else(|| "prepared program quote is unavailable or expired".to_string())?; - if stored.prepared.account_index != params.account_index { - let message = format!( - "quote {} was prepared for account index {}, not {}", - params.quote_id, stored.prepared.account_index, params.account_index - ); - store_quote(stored, now); - return Err(message); - } - let origin = ExecutionOrigin::rpc(); - let prepared = stored.prepared.clone(); - let chain = chain_name(prepared.chain); - let (ledger, _) = ledger_records(&config)?; - let reserved = ledger - .reserve(|records| { - if let Some(refused) = origin_refusal(&origin) { - return Err(refused); - } - if let Some(earlier) = records.iter().rev().find(|record| { - record.quote_id == prepared.quote_id && record.status.counts_against_caps() - }) { - return Err(refusal( - RefusalKind::AlreadyAttempted, - format!( - "quote {} was already executed (status {:?}); it is never retried", - prepared.quote_id, earlier.status - ), - )); - } - evaluate_program( - &config.wallet_policy, - chain, - prepared.account_index, - &prepared.summary, - records, - now, - )?; - Ok(program_record(&prepared, &origin, LedgerStatus::Pending, now)) - }) - .map_err(|error| format!("wallet spend ledger is unavailable: {error:#}"))?; - let mut record = match reserved { - Ok(record) => record, - Err(refused) => { - tracing::info!( - quote_id = %prepared.quote_id, - kind = ?refused.kind, - "{LOG_PREFIX} execute refused" - ); - let mut record = program_record(&prepared, &origin, LedgerStatus::Refused, now); - record.error = Some(refused.message.clone()); - if let Err(error) = ledger.put(&record) { - tracing::warn!(%error, "{LOG_PREFIX} could not record a refusal"); - } - if refused.kind != RefusalKind::AlreadyAttempted { - store_quote(stored, now); - } - return Err(refused.to_string()); - } - }; - tracing::info!( - quote_id = %prepared.quote_id, - record_id = %record.id, - "{LOG_PREFIX} execute recorded as pending" - ); - - let result = sign_and_send(ctx, &config, &stored).await; - record.updated_at_ms = super::policy::wall_clock_ms().max(now); - match &result { - Ok(hash) => { - record.status = LedgerStatus::Broadcast; - record.transaction_hash = Some(hash.clone()); - } - Err(error) => { - record.status = LedgerStatus::InDoubt; - record.error = Some(error.clone()); - } - } - if let Err(error) = ledger.put(&record) { - tracing::warn!(%error, record_id = %record.id, "{LOG_PREFIX} could not update the ledger"); - } - let transaction_hash = result?; - Ok(Outcome::new( - ExecutedProgram { - quote_id: prepared.quote_id, - chain: prepared.chain, - account_index: prepared.account_index, - address: prepared.address, - transaction_hash, - }, - vec!["wallet program transaction broadcast".to_string()], - )) -} - -async fn sign_and_send( - ctx: &DispatchCtx, - config: &crate::config::Config, - stored: &StoredQuote, -) -> Result { - let prepared = &stored.prepared; - let material = - super::ops::secret_material(ctx, prepared.chain, prepared.account_index).await?; - let mnemonic = Zeroizing::new( - crate::credentials::ops::decrypt_secret(config, &material.encrypted_mnemonic) - .await - .map_err(|error| format!("failed to decrypt the recovery phrase: {error}"))? - .value, - ); - let secret = SecretMaterial { - mnemonic: mnemonic.to_string(), - derivation_path: material.derivation_path, - chain: prepared.chain.to_chain(), - }; - let signed = crate::modules::wallet::sign_message( - config, - &secret, - &stored.decoded.message, - Scheme::Ed25519, - ) - .await; - let mut secret = secret; - zeroize::Zeroize::zeroize(&mut secret.mnemonic); - let signature = match signed.map_err(|error| error.to_string())? { - Signature::Ed25519 { signature_hex } => { - let bytes = hex::decode(signature_hex.trim()) - .map_err(|_| "wallet module returned a malformed signature".to_string())?; - <[u8; 64]>::try_from(bytes.as_slice()) - .map_err(|_| "wallet module returned a signature of the wrong length".to_string())? - } - _ => return Err("wallet module returned a non-ed25519 signature".to_string()), - }; - let signed_transaction = attach_signature(&stored.transaction, &stored.decoded, &signature)?; - let url = solana_rpc_url(ctx).await?; - let encoded = base64::engine::general_purpose::STANDARD.encode(signed_transaction); - let hash: String = super::rpc::rpc_call_to( - &url, - "sendTransaction", - serde_json::json!([encoded, {"encoding": "base64", "preflightCommitment": "confirmed"}]), - ) - .await?; - let expected = base58(&signature); - if hash != expected { - tracing::warn!("{LOG_PREFIX} RPC returned a signature other than the one attached"); - } - Ok(hash) -} - -/// The Solana endpoint: the host override when one is configured, otherwise -/// the module's default for the configured cluster. -async fn solana_rpc_url(ctx: &DispatchCtx) -> Result { - if let Some(url) = super::endpoints::override_for_endpoint(RpcEndpointKey::Solana) { - return Ok(url); - } - super::execution::network_defaults(ctx) - .await? - .value - .into_iter() - .find(|row| row.chain == WalletChain::Solana && row.rpc_source == RpcSource::Default) - .map(|row| row.rpc_url) - .ok_or_else(|| "the wallet module reports no default Solana endpoint".to_string()) -} +pub(crate) use ops::{has_quote_for_test, program_record}; #[cfg(test)] -#[path = "program_tests.rs"] +#[path = "mod_tests.rs"] mod tests; diff --git a/crates/openhuman-core/src/web3/wallet/program_tests.rs b/crates/openhuman-core/src/web3/wallet/program/mod_tests.rs similarity index 100% rename from crates/openhuman-core/src/web3/wallet/program_tests.rs rename to crates/openhuman-core/src/web3/wallet/program/mod_tests.rs diff --git a/crates/openhuman-core/src/web3/wallet/program/ops.rs b/crates/openhuman-core/src/web3/wallet/program/ops.rs new file mode 100644 index 00000000000..c8a464ab465 --- /dev/null +++ b/crates/openhuman-core/src/web3/wallet/program/ops.rs @@ -0,0 +1,404 @@ +//! Program quotes and their execution: `wallet.prepare_program` and +//! `wallet.execute_prepared_program` (see the parent module). + +use std::collections::HashMap; +use std::sync::Mutex; + +use base64::Engine as _; +use once_cell::sync::Lazy; +use serde::{Deserialize, Serialize}; +use tinywallet_bus::wire::{RpcEndpointKey, RpcSource, Scheme, SecretMaterial, Signature}; +use zeroize::Zeroizing; + +use crate::config::schema::WalletPolicyConfig; +use crate::core::runtime::DispatchCtx; +use crate::core::Outcome; + +use super::super::ledger::{LedgerKind, LedgerRecord, LedgerStatus, SpendLedger}; +use super::super::ops::WalletChain; +use super::super::policy::{origin_refusal, refusal, ExecutionOrigin, RefusalKind}; +use super::{ + attach_signature, base58, decode_transaction, evaluate_program, summarize, DecodedTransaction, + ProgramTransactionSummary, LOG_PREFIX, QUOTE_PREFIX, QUOTE_TTL_MS, +}; + +// ── Quotes ────────────────────────────────────────────────────────────────── + +/// A prepared program transaction, as returned to the caller. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct PreparedProgram { + pub quote_id: String, + pub chain: WalletChain, + pub account_index: u32, + /// The signing account's address (the fee payer). + pub address: String, + pub summary: ProgramTransactionSummary, + pub created_at_ms: u64, + pub expires_at_ms: u64, +} + +/// The result of executing a prepared program transaction. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ExecutedProgram { + pub quote_id: String, + pub chain: WalletChain, + pub account_index: u32, + pub address: String, + /// The transaction signature (base58), as the RPC accepted it. + pub transaction_hash: String, +} + +/// `wallet.prepare_program` parameters. +#[derive(Debug, Clone, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct PrepareProgramParams { + #[serde(alias = "account_index")] + pub account_index: u32, + /// Base64 of the unsigned transaction's wire bytes (signature slots + /// zeroed), e.g. `transaction.serialize({requireAllSignatures: false})`. + pub transaction: String, +} + +/// `wallet.execute_prepared_program` parameters. +#[derive(Debug, Clone, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct ExecuteProgramParams { + #[serde(alias = "account_index")] + pub account_index: u32, + #[serde(alias = "quote_id")] + pub quote_id: String, +} + +#[derive(Clone)] +struct StoredQuote { + prepared: PreparedProgram, + transaction: Vec, + decoded: DecodedTransaction, +} + +static QUOTES: Lazy>> = Lazy::new(|| Mutex::new(HashMap::new())); + +fn store_quote(quote: StoredQuote, now_ms: u64) { + if let Ok(mut quotes) = QUOTES.lock() { + quotes.retain(|_, stored| stored.prepared.expires_at_ms > now_ms); + quotes.insert(quote.prepared.quote_id.clone(), quote); + } +} + +fn take_quote(quote_id: &str) -> Option { + QUOTES.lock().ok()?.remove(quote_id) +} + +/// Prepare quotes currently held (test support). +#[cfg(test)] +pub(crate) fn has_quote_for_test(quote_id: &str) -> bool { + QUOTES + .lock() + .is_ok_and(|quotes| quotes.contains_key(quote_id)) +} + +fn chain_name(chain: WalletChain) -> &'static str { + chain.as_str() +} + +fn ledger_records(config: &crate::config::Config) -> Result<(SpendLedger, Vec), String> { + let ledger = SpendLedger::open(&config.workspace_dir) + .map_err(|error| format!("wallet spend ledger is unavailable: {error:#}"))?; + let records = ledger + .records() + .map_err(|error| format!("wallet spend ledger is unavailable: {error:#}"))?; + Ok((ledger, records)) +} + +/// Decode, summarise and check one transaction, then store it as a quote. +/// The policy section is checked before any key derivation. +/// +/// # Errors +/// +/// A policy refusal (prefixed `WALLET_POLICY_REFUSED:`), malformed input, or +/// a wallet that cannot provide the account. +pub async fn prepare_program( + ctx: &DispatchCtx, + params: PrepareProgramParams, +) -> Result, String> { + let chain = WalletChain::Solana; + let config = ctx.load_config().await?; + let key = WalletPolicyConfig::account_key(chain_name(chain), params.account_index); + if config + .wallet_policy + .account_policy(chain_name(chain), params.account_index) + .is_none() + { + return Err(refusal( + RefusalKind::AccountNotAllowed, + format!("account {key} has no [wallet_policy.accounts.{key}] section"), + ) + .to_string()); + } + let transaction = base64::engine::general_purpose::STANDARD + .decode(params.transaction.trim()) + .map_err(|error| format!("transaction is not valid base64: {error}"))?; + let decoded = decode_transaction(&transaction)?; + let account = super::super::ops::ensure_account(ctx, chain, params.account_index).await?; + let summary = summarize(&decoded, &account.address).map_err(|refused| refused.to_string())?; + let now = super::super::policy::wall_clock_ms(); + let (_, records) = ledger_records(&config)?; + evaluate_program( + &config.wallet_policy, + chain_name(chain), + params.account_index, + &summary, + &records, + now, + ) + .map_err(|refused| { + tracing::info!(account = %key, kind = ?refused.kind, "{LOG_PREFIX} prepare refused"); + refused.to_string() + })?; + let prepared = PreparedProgram { + quote_id: format!("{QUOTE_PREFIX}{}", uuid::Uuid::new_v4()), + chain, + account_index: params.account_index, + address: account.address, + summary, + created_at_ms: now, + expires_at_ms: now + QUOTE_TTL_MS, + }; + tracing::info!( + quote_id = %prepared.quote_id, + account = %key, + programs = prepared.summary.programs.len(), + movements = prepared.summary.movements.len(), + "{LOG_PREFIX} prepared" + ); + store_quote( + StoredQuote { + prepared: prepared.clone(), + transaction, + decoded, + }, + now, + ); + Ok(Outcome::new( + prepared, + vec!["wallet program transaction prepared".to_string()], + )) +} + +/// The ledger record of one program execute. +fn program_record( + prepared: &PreparedProgram, + origin: &ExecutionOrigin, + status: LedgerStatus, + now_ms: u64, +) -> LedgerRecord { + let total = prepared.summary.totals.first(); + let destination = match prepared.summary.movements.as_slice() { + [] => String::new(), + [only] => only.destination.clone(), + [first, rest @ ..] if rest.iter().all(|m| m.destination == first.destination) => { + first.destination.clone() + } + _ => "multiple".to_string(), + }; + LedgerRecord { + id: uuid::Uuid::new_v4().to_string(), + quote_id: prepared.quote_id.clone(), + created_at_ms: now_ms, + updated_at_ms: now_ms, + origin: origin.label().into(), + origin_class: origin.class().into(), + policy_applied: true, + chain: chain_name(prepared.chain).to_string(), + evm_network: None, + asset_symbol: if total.is_some() { "SPL" } else { "" }.to_string(), + token_address: total.map(|total| total.mint.clone()), + to_address: destination, + amount_raw: total.map_or_else(|| "0".to_string(), |total| total.amount_raw.clone()), + status, + transaction_hash: None, + error: None, + kind: LedgerKind::Program, + account_index: prepared.account_index, + } +} + +/// Execute a prepared program transaction: re-check and reserve under the +/// policy, sign in the module, send. A quote is single-use once an attempt +/// reached signing. +/// +/// # Errors +/// +/// A policy refusal (prefixed `WALLET_POLICY_REFUSED:`), an unknown or +/// expired quote, or the signing or send error (the attempt is then recorded +/// `in_doubt` and never retried). +pub async fn execute_prepared_program( + ctx: &DispatchCtx, + params: ExecuteProgramParams, +) -> Result, String> { + let config = ctx.load_config().await?; + let now = super::super::policy::wall_clock_ms(); + let stored = take_quote(¶ms.quote_id) + .filter(|stored| stored.prepared.expires_at_ms > now) + .ok_or_else(|| "prepared program quote is unavailable or expired".to_string())?; + if stored.prepared.account_index != params.account_index { + let message = format!( + "quote {} was prepared for account index {}, not {}", + params.quote_id, stored.prepared.account_index, params.account_index + ); + store_quote(stored, now); + return Err(message); + } + let origin = ExecutionOrigin::rpc(); + let prepared = stored.prepared.clone(); + let chain = chain_name(prepared.chain); + let (ledger, _) = ledger_records(&config)?; + let reserved = ledger + .reserve(|records| { + if let Some(refused) = origin_refusal(&origin) { + return Err(refused); + } + if let Some(earlier) = records.iter().rev().find(|record| { + record.quote_id == prepared.quote_id && record.status.counts_against_caps() + }) { + return Err(refusal( + RefusalKind::AlreadyAttempted, + format!( + "quote {} was already executed (status {:?}); it is never retried", + prepared.quote_id, earlier.status + ), + )); + } + evaluate_program( + &config.wallet_policy, + chain, + prepared.account_index, + &prepared.summary, + records, + now, + )?; + Ok(program_record(&prepared, &origin, LedgerStatus::Pending, now)) + }) + .map_err(|error| format!("wallet spend ledger is unavailable: {error:#}"))?; + let mut record = match reserved { + Ok(record) => record, + Err(refused) => { + tracing::info!( + quote_id = %prepared.quote_id, + kind = ?refused.kind, + "{LOG_PREFIX} execute refused" + ); + let mut record = program_record(&prepared, &origin, LedgerStatus::Refused, now); + record.error = Some(refused.message.clone()); + if let Err(error) = ledger.put(&record) { + tracing::warn!(%error, "{LOG_PREFIX} could not record a refusal"); + } + if refused.kind != RefusalKind::AlreadyAttempted { + store_quote(stored, now); + } + return Err(refused.to_string()); + } + }; + tracing::info!( + quote_id = %prepared.quote_id, + record_id = %record.id, + "{LOG_PREFIX} execute recorded as pending" + ); + + let result = sign_and_send(ctx, &config, &stored).await; + record.updated_at_ms = super::super::policy::wall_clock_ms().max(now); + match &result { + Ok(hash) => { + record.status = LedgerStatus::Broadcast; + record.transaction_hash = Some(hash.clone()); + } + Err(error) => { + record.status = LedgerStatus::InDoubt; + record.error = Some(error.clone()); + } + } + if let Err(error) = ledger.put(&record) { + tracing::warn!(%error, record_id = %record.id, "{LOG_PREFIX} could not update the ledger"); + } + let transaction_hash = result?; + Ok(Outcome::new( + ExecutedProgram { + quote_id: prepared.quote_id, + chain: prepared.chain, + account_index: prepared.account_index, + address: prepared.address, + transaction_hash, + }, + vec!["wallet program transaction broadcast".to_string()], + )) +} + +async fn sign_and_send( + ctx: &DispatchCtx, + config: &crate::config::Config, + stored: &StoredQuote, +) -> Result { + let prepared = &stored.prepared; + let material = + super::super::ops::secret_material(ctx, prepared.chain, prepared.account_index).await?; + let mnemonic = Zeroizing::new( + crate::credentials::ops::decrypt_secret(config, &material.encrypted_mnemonic) + .await + .map_err(|error| format!("failed to decrypt the recovery phrase: {error}"))? + .value, + ); + let secret = SecretMaterial { + mnemonic: mnemonic.to_string(), + derivation_path: material.derivation_path, + chain: prepared.chain.to_chain(), + }; + let signed = crate::modules::wallet::sign_message( + config, + &secret, + &stored.decoded.message, + Scheme::Ed25519, + ) + .await; + let mut secret = secret; + zeroize::Zeroize::zeroize(&mut secret.mnemonic); + let signature = match signed.map_err(|error| error.to_string())? { + Signature::Ed25519 { signature_hex } => { + let bytes = hex::decode(signature_hex.trim()) + .map_err(|_| "wallet module returned a malformed signature".to_string())?; + <[u8; 64]>::try_from(bytes.as_slice()) + .map_err(|_| "wallet module returned a signature of the wrong length".to_string())? + } + _ => return Err("wallet module returned a non-ed25519 signature".to_string()), + }; + let signed_transaction = attach_signature(&stored.transaction, &stored.decoded, &signature)?; + let url = solana_rpc_url(ctx).await?; + let encoded = base64::engine::general_purpose::STANDARD.encode(signed_transaction); + let hash: String = super::super::rpc::rpc_call_to( + &url, + "sendTransaction", + serde_json::json!([encoded, {"encoding": "base64", "preflightCommitment": "confirmed"}]), + ) + .await?; + let expected = base58(&signature); + if hash != expected { + tracing::warn!("{LOG_PREFIX} RPC returned a signature other than the one attached"); + } + Ok(hash) +} + +/// The Solana endpoint: the host override when one is configured, otherwise +/// the module's default for the configured cluster. +async fn solana_rpc_url(ctx: &DispatchCtx) -> Result { + if let Some(url) = super::super::endpoints::override_for_endpoint(RpcEndpointKey::Solana) { + return Ok(url); + } + super::super::execution::network_defaults(ctx) + .await? + .value + .into_iter() + .find(|row| row.chain == WalletChain::Solana && row.rpc_source == RpcSource::Default) + .map(|row| row.rpc_url) + .ok_or_else(|| "the wallet module reports no default Solana endpoint".to_string()) +} From dfdb5db4d2c3561c0231f5e39c7c80b20b8f672f Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Sun, 15 Nov 2026 22:01:15 +0000 Subject: [PATCH 19/32] refactor(wallet): split program wallet module into focused submodules Moved the program wallet implementation out of a single module into dedicated ops and test files, leaving mod.rs to hold only shared types and constants. This keeps the pure decoding and policy logic separate from the chain-facing code so each part can be tested in isolation. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../src/config/schema/wallet_policy_tests.rs | 5 +- .../provider/factory/routing_tests.rs | 2 +- crates/openhuman-core/src/web3/wallet/mod.rs | 4 +- crates/openhuman-core/src/web3/wallet/ops.rs | 5 +- .../src/web3/wallet/ops_tests.rs | 12 +- .../src/web3/wallet/program/mod.rs | 40 +++--- .../src/web3/wallet/program/mod_tests.rs | 133 +++++++++++++++--- .../src/web3/wallet/program/ops.rs | 13 +- 8 files changed, 160 insertions(+), 54 deletions(-) diff --git a/crates/openhuman-core/src/config/schema/wallet_policy_tests.rs b/crates/openhuman-core/src/config/schema/wallet_policy_tests.rs index c331ca504d7..e6b782d2521 100644 --- a/crates/openhuman-core/src/config/schema/wallet_policy_tests.rs +++ b/crates/openhuman-core/src/config/schema/wallet_policy_tests.rs @@ -134,6 +134,9 @@ fn a_mint_cap_without_both_caps_or_with_a_typo_fails_to_parse() { "mint = \"m\"\nper_tx_max_raw = 1\ndaily_max_raw = 1\ndaily_max_raww = 1\n", ] { let text = format!("[[wallet_policy.accounts.solana_1.mints]]\n{body}"); - assert!(toml::from_str::(&text).is_err(), "{body}"); + assert!( + toml::from_str::(&text).is_err(), + "{body}" + ); } } diff --git a/crates/openhuman-core/src/inference/provider/factory/routing_tests.rs b/crates/openhuman-core/src/inference/provider/factory/routing_tests.rs index 79e6c0588db..2d0f60fc5df 100644 --- a/crates/openhuman-core/src/inference/provider/factory/routing_tests.rs +++ b/crates/openhuman-core/src/inference/provider/factory/routing_tests.rs @@ -1,6 +1,6 @@ use super::*; -use crate::config::Config; use crate::config::schema::cloud_providers::{AuthStyle, CloudProviderCreds}; +use crate::config::Config; use crate::inference::provider::factory::resolves_to_managed_backend; fn byok_openai_compatible_entry() -> CloudProviderCreds { diff --git a/crates/openhuman-core/src/web3/wallet/mod.rs b/crates/openhuman-core/src/web3/wallet/mod.rs index 23a22a9ceb6..5b12c0d915d 100644 --- a/crates/openhuman-core/src/web3/wallet/mod.rs +++ b/crates/openhuman-core/src/web3/wallet/mod.rs @@ -76,8 +76,8 @@ pub use execution::{ }; #[cfg(feature = "web3")] pub use ops::{ - derive_recovery_material, ensure_account, generate_recovery_phrase, reveal_recovery_phrase, setup, status, - validate_recovery_phrase, GeneratedRecoveryPhrase, RecoveryPhraseValidation, + derive_recovery_material, ensure_account, generate_recovery_phrase, reveal_recovery_phrase, + setup, status, validate_recovery_phrase, GeneratedRecoveryPhrase, RecoveryPhraseValidation, RevealRecoveryPhraseResult, WalletAccount, WalletChain, WalletRecoveryMaterial, WalletSetupParams, WalletSetupSource, WalletStatus, WALLET_NOT_CONFIGURED_MESSAGE, }; diff --git a/crates/openhuman-core/src/web3/wallet/ops.rs b/crates/openhuman-core/src/web3/wallet/ops.rs index 398f809c3b8..7d983973126 100644 --- a/crates/openhuman-core/src/web3/wallet/ops.rs +++ b/crates/openhuman-core/src/web3/wallet/ops.rs @@ -594,7 +594,10 @@ pub async fn ensure_account( .into_iter() .find(|account| account.chain == chain && account.index == index) else { - return Err(format!("no derivation for '{}' index {index}", chain.as_str())); + return Err(format!( + "no derivation for '{}' index {index}", + chain.as_str() + )); }; let mnemonic = Zeroizing::new( crate::credentials::ops::decrypt_secret(&config, &encrypted_mnemonic) diff --git a/crates/openhuman-core/src/web3/wallet/ops_tests.rs b/crates/openhuman-core/src/web3/wallet/ops_tests.rs index 6a6d9f75774..a7dfd288bd9 100644 --- a/crates/openhuman-core/src/web3/wallet/ops_tests.rs +++ b/crates/openhuman-core/src/web3/wallet/ops_tests.rs @@ -305,7 +305,13 @@ fn primary_accounts_are_unchanged() { let primary: Vec<_> = plan .iter() .take(4) - .map(|account| (account.chain, account.derivation_path.as_str(), account.index)) + .map(|account| { + ( + account.chain, + account.derivation_path.as_str(), + account.index, + ) + }) .collect(); assert_eq!( primary, @@ -378,7 +384,9 @@ fn validate_setup_rejects_unknown_or_duplicate_secondary_accounts() { // A secondary account never stands in for a missing primary one. let mut params = sample_params(); - params.accounts.retain(|account| account.chain != WalletChain::Solana); + params + .accounts + .retain(|account| account.chain != WalletChain::Solana); params.accounts.push(giveaway_account()); assert!(validate_setup(¶ms) .expect_err("no primary solana") diff --git a/crates/openhuman-core/src/web3/wallet/program/mod.rs b/crates/openhuman-core/src/web3/wallet/program/mod.rs index 97695e03734..49786267773 100644 --- a/crates/openhuman-core/src/web3/wallet/program/mod.rs +++ b/crates/openhuman-core/src/web3/wallet/program/mod.rs @@ -38,22 +38,14 @@ //! The pure parts (decoding, summarising, the policy decision) are separate //! functions so they are tested without a module or a chain. -use std::collections::{BTreeMap, HashMap}; -use std::sync::Mutex; +use std::collections::BTreeMap; -use base64::Engine as _; -use once_cell::sync::Lazy; use serde::{Deserialize, Serialize}; -use tinywallet_bus::wire::{RpcEndpointKey, RpcSource, Scheme, SecretMaterial, Signature}; -use zeroize::Zeroizing; use crate::config::schema::WalletPolicyConfig; -use crate::core::runtime::DispatchCtx; -use crate::core::Outcome; -use super::ledger::{LedgerKind, LedgerRecord, LedgerStatus, SpendLedger}; -use super::ops::WalletChain; -use super::policy::{origin_refusal, refusal, ExecutionOrigin, PolicyRefusal, RefusalKind}; +use super::ledger::{LedgerKind, LedgerRecord}; +use super::policy::{refusal, PolicyRefusal, RefusalKind}; /// The System program. pub const SYSTEM_PROGRAM: &str = "11111111111111111111111111111111"; @@ -73,10 +65,10 @@ pub const MAX_TRANSACTION_BYTES: usize = 1232; /// Prefix of every program quote id. pub const QUOTE_PREFIX: &str = "prog-"; -const DAY_MS: u64 = 24 * 60 * 60 * 1000; +pub(super) const DAY_MS: u64 = 24 * 60 * 60 * 1000; /// SPL Token `TransferChecked`. const TOKEN_TRANSFER_CHECKED: u8 = 12; -const LOG_PREFIX: &str = "[wallet:program]"; +pub(super) const LOG_PREFIX: &str = "[wallet:program]"; // ── Decoding ──────────────────────────────────────────────────────────────── @@ -169,7 +161,11 @@ pub fn decode_transaction(bytes: &[u8]) -> Result { let mut reader = Reader { bytes, pos: 0 }; let signature_count = reader.compact_u16()?; let signatures_offset = reader.pos; - reader.take(signature_count.checked_mul(64).ok_or("too many signatures")?)?; + reader.take( + signature_count + .checked_mul(64) + .ok_or("too many signatures")?, + )?; let message_start = reader.pos; let first = *bytes @@ -251,7 +247,7 @@ pub fn attach_signature( Ok(signed) } -fn base58(bytes: &[u8]) -> String { +pub(super) fn base58(bytes: &[u8]) -> String { bs58::encode(bytes).into_string() } @@ -378,7 +374,8 @@ pub fn summarize( ))); } TOKEN_PROGRAM | TOKEN_2022_PROGRAM => { - let movement = token_transfer_checked(position, &program_id, instruction, &accounts)?; + let movement = + token_transfer_checked(position, &program_id, instruction, &accounts)?; let amount: u128 = movement.amount_raw.parse().unwrap_or(u128::MAX); let total = totals.entry(movement.mint.clone()).or_insert_with(|| { mint_order.push(movement.mint.clone()); @@ -486,11 +483,12 @@ pub fn evaluate_program( format!("account {key} has no [wallet_policy.accounts.{key}] section"), )); }; - if let Some(program) = summary - .programs - .iter() - .find(|program| !section.allowed_programs.iter().any(|allowed| allowed == *program)) - { + if let Some(program) = summary.programs.iter().find(|program| { + !section + .allowed_programs + .iter() + .any(|allowed| allowed == *program) + }) { return Err(refusal( RefusalKind::ProgramNotAllowed, format!("program {program} is not in {key}'s allowed_programs"), diff --git a/crates/openhuman-core/src/web3/wallet/program/mod_tests.rs b/crates/openhuman-core/src/web3/wallet/program/mod_tests.rs index d3212499e8d..355faaca91e 100644 --- a/crates/openhuman-core/src/web3/wallet/program/mod_tests.rs +++ b/crates/openhuman-core/src/web3/wallet/program/mod_tests.rs @@ -1,5 +1,10 @@ use super::*; use crate::config::schema::{WalletAccountPolicy, WalletMintCap}; +use crate::core::runtime::DispatchCtx; +use crate::web3::wallet::ledger::LedgerStatus; +use crate::web3::wallet::ops::WalletChain; +use crate::web3::wallet::policy::ExecutionOrigin; +use base64::Engine as _; /// `m/44'/501'/1'/0'` of the BIP-39 test phrase (see `ops_tests.rs`). const SIGNER: &str = "Hh8QwFUA6MtVu1qAoq12ucvFHNwCcVTV7hpWjeY1Hztb"; @@ -45,7 +50,12 @@ struct Ix { } /// Serialize an unsigned transaction with `signer` as account 0. -fn build(signer: [u8; 32], required: u8, instructions: &[Ix], v0_lookups: Option) -> Vec { +fn build( + signer: [u8; 32], + required: u8, + instructions: &[Ix], + v0_lookups: Option, +) -> Vec { let mut keys = vec![signer]; let index_of = |key: [u8; 32], keys: &mut Vec<[u8; 32]>| -> u8 { if let Some(position) = keys.iter().position(|existing| *existing == key) { @@ -57,7 +67,11 @@ fn build(signer: [u8; 32], required: u8, instructions: &[Ix], v0_lookups: Option let compiled: Vec<(u8, Vec, Vec)> = instructions .iter() .map(|ix| { - let accounts = ix.accounts.iter().map(|k| index_of(*k, &mut keys)).collect(); + let accounts = ix + .accounts + .iter() + .map(|k| index_of(*k, &mut keys)) + .collect(); let program = index_of(ix.program, &mut keys); (program, accounts, ix.data.clone()) }) @@ -170,7 +184,11 @@ fn a_distributor_funding_transaction_decodes_into_its_summary() { let tx = build( key(SIGNER), 1, - &[ata_create(), transfer_checked(&mint(), 600), distributor_call()], + &[ + ata_create(), + transfer_checked(&mint(), 600), + distributor_call(), + ], None, ); let decoded = decode_transaction(&tx).unwrap(); @@ -191,7 +209,13 @@ fn a_distributor_funding_transaction_decodes_into_its_summary() { assert_eq!(summary.movements[0].amount_raw, "600"); assert_eq!(summary.movements[0].decimals, 6); assert_eq!(summary.movements[0].authority, SIGNER); - assert_eq!(summary.totals, vec![MintTotal { mint: mint(), amount_raw: "600".into() }]); + assert_eq!( + summary.totals, + vec![MintTotal { + mint: mint(), + amount_raw: "600".into() + }] + ); assert_eq!(summary.instructions[2].data_hex, "aabb"); assert_eq!( evaluate_program(&policy(), "solana", 1, &summary, &[], NOW), @@ -224,13 +248,27 @@ fn malformed_bytes_are_rejected() { fn an_account_without_a_policy_section_is_refused() { let summary = summary_of(&[distributor_call()]); assert_eq!( - refusal_kind(evaluate_program(&WalletPolicyConfig::default(), "solana", 1, &summary, &[], NOW)), + refusal_kind(evaluate_program( + &WalletPolicyConfig::default(), + "solana", + 1, + &summary, + &[], + NOW + )), RefusalKind::AccountNotAllowed ); // A section for index 1 does not open index 0 or index 2. for index in [0, 2] { assert_eq!( - refusal_kind(evaluate_program(&policy(), "solana", index, &summary, &[], NOW)), + refusal_kind(evaluate_program( + &policy(), + "solana", + index, + &summary, + &[], + NOW + )), RefusalKind::AccountNotAllowed ); } @@ -246,8 +284,14 @@ fn an_unlisted_program_is_refused() { let summary = summary_of(&[distributor_call(), unlisted]); let refused = evaluate_program(&policy(), "solana", 1, &summary, &[], NOW).unwrap_err(); assert_eq!(refused.kind, RefusalKind::ProgramNotAllowed); - assert!(refused.message.contains(&base58(&filled(42))), "{}", refused.message); - assert!(refused.to_string().starts_with(super::super::policy::POLICY_REFUSED_PREFIX)); + assert!( + refused.message.contains(&base58(&filled(42))), + "{}", + refused.message + ); + assert!(refused + .to_string() + .starts_with(crate::web3::wallet::policy::POLICY_REFUSED_PREFIX)); } #[test] @@ -263,7 +307,10 @@ fn a_transfer_over_the_per_transaction_cap_is_refused() { RefusalKind::PerTransaction ); let at_cap = summary_of(&[transfer_checked(&mint(), 1_000)]); - assert_eq!(evaluate_program(&policy(), "solana", 1, &at_cap, &[], NOW), Ok(())); + assert_eq!( + evaluate_program(&policy(), "solana", 1, &at_cap, &[], NOW), + Ok(()) + ); } #[test] @@ -278,15 +325,29 @@ fn the_rolling_day_cap_counts_only_this_accounts_program_records() { ]; let refused = evaluate_program(&policy(), "solana", 1, &summary, &records, NOW).unwrap_err(); assert_eq!(refused.kind, RefusalKind::Daily); - assert!(refused.message.contains("1000 already spent"), "{}", refused.message); + assert!( + refused.message.contains("1000 already spent"), + "{}", + refused.message + ); let small = summary_of(&[transfer_checked(&mint(), 500)]); - assert_eq!(evaluate_program(&policy(), "solana", 1, &small, &records, NOW), Ok(())); + assert_eq!( + evaluate_program(&policy(), "solana", 1, &small, &records, NOW), + Ok(()) + ); // An in-doubt attempt counts as spent. let mut in_doubt = records.clone(); in_doubt.push(spent(1, NOW - 10, 1, LedgerStatus::InDoubt)); assert_eq!( - refusal_kind(evaluate_program(&policy(), "solana", 1, &small, &in_doubt, NOW)), + refusal_kind(evaluate_program( + &policy(), + "solana", + 1, + &small, + &in_doubt, + NOW + )), RefusalKind::Daily ); } @@ -303,11 +364,16 @@ fn an_unlisted_mint_is_refused() { #[test] fn two_mints_in_one_transaction_are_refused() { let mut policy = policy(); - policy.accounts.get_mut("solana_1").unwrap().mints.push(WalletMintCap { - mint: other_mint(), - per_tx_max_raw: 1_000, - daily_max_raw: 1_000, - }); + policy + .accounts + .get_mut("solana_1") + .unwrap() + .mints + .push(WalletMintCap { + mint: other_mint(), + per_tx_max_raw: 1_000, + daily_max_raw: 1_000, + }); let summary = summary_of(&[ transfer_checked(&mint(), 1), transfer_checked(&other_mint(), 1), @@ -327,15 +393,24 @@ fn summarize_kind(tx: &[u8], signer: &str) -> RefusalKind { #[test] fn a_transaction_another_key_pays_for_or_cosigns_is_refused() { let tx = build(filled(4), 1, &[distributor_call()], None); - assert_eq!(summarize_kind(&tx, SIGNER), RefusalKind::TransactionNotAllowed); + assert_eq!( + summarize_kind(&tx, SIGNER), + RefusalKind::TransactionNotAllowed + ); let cosigned = build(key(SIGNER), 2, &[distributor_call()], None); - assert_eq!(summarize_kind(&cosigned, SIGNER), RefusalKind::TransactionNotAllowed); + assert_eq!( + summarize_kind(&cosigned, SIGNER), + RefusalKind::TransactionNotAllowed + ); } #[test] fn address_lookup_tables_are_refused() { let tx = build(key(SIGNER), 1, &[distributor_call()], Some(1)); - assert_eq!(summarize_kind(&tx, SIGNER), RefusalKind::TransactionNotAllowed); + assert_eq!( + summarize_kind(&tx, SIGNER), + RefusalKind::TransactionNotAllowed + ); } #[test] @@ -365,9 +440,18 @@ fn system_and_unaccountable_token_instructions_are_refused_whatever_the_policy() accounts: vec![key(SIGNER)], data: vec![2], }; - for ix in [system_transfer, plain_transfer, approve, set_authority, recover_nested] { + for ix in [ + system_transfer, + plain_transfer, + approve, + set_authority, + recover_nested, + ] { let tx = build(key(SIGNER), 1, &[ix], None); - assert_eq!(summarize_kind(&tx, SIGNER), RefusalKind::InstructionNotAllowed); + assert_eq!( + summarize_kind(&tx, SIGNER), + RefusalKind::InstructionNotAllowed + ); } } @@ -378,7 +462,10 @@ fn the_signature_lands_in_slot_zero_and_the_message_is_untouched() { let signed = attach_signature(&tx, &decoded, &[0xab; 64]).unwrap(); assert_eq!(&signed[1..65], &[0xab; 64][..]); assert_eq!(&signed[65..], decoded.message.as_slice()); - assert_eq!(decode_transaction(&signed).unwrap().message, decoded.message); + assert_eq!( + decode_transaction(&signed).unwrap().message, + decoded.message + ); } #[test] diff --git a/crates/openhuman-core/src/web3/wallet/program/ops.rs b/crates/openhuman-core/src/web3/wallet/program/ops.rs index c8a464ab465..4a9dc39ca2b 100644 --- a/crates/openhuman-core/src/web3/wallet/program/ops.rs +++ b/crates/openhuman-core/src/web3/wallet/program/ops.rs @@ -103,7 +103,9 @@ fn chain_name(chain: WalletChain) -> &'static str { chain.as_str() } -fn ledger_records(config: &crate::config::Config) -> Result<(SpendLedger, Vec), String> { +fn ledger_records( + config: &crate::config::Config, +) -> Result<(SpendLedger, Vec), String> { let ledger = SpendLedger::open(&config.workspace_dir) .map_err(|error| format!("wallet spend ledger is unavailable: {error:#}"))?; let records = ledger @@ -188,7 +190,7 @@ pub async fn prepare_program( } /// The ledger record of one program execute. -fn program_record( +pub(crate) fn program_record( prepared: &PreparedProgram, origin: &ExecutionOrigin, status: LedgerStatus, @@ -279,7 +281,12 @@ pub async fn execute_prepared_program( records, now, )?; - Ok(program_record(&prepared, &origin, LedgerStatus::Pending, now)) + Ok(program_record( + &prepared, + &origin, + LedgerStatus::Pending, + now, + )) }) .map_err(|error| format!("wallet spend ledger is unavailable: {error:#}"))?; let mut record = match reserved { From aeaef5ac78345ba2b3cc9e9010c69355cd271f3f Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Sun, 15 Nov 2026 22:04:13 +0000 Subject: [PATCH 20/32] refactor(web3): use match guard for associated token program check The associated token program arm now uses a match guard so only disallowed instruction data falls through to the error, letting valid creates continue to the default arm. This flattens the nested conditional without changing behaviour. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../openhuman-core/src/web3/wallet/program/mod.rs | 14 ++++++-------- 1 file changed, 6 insertions(+), 8 deletions(-) diff --git a/crates/openhuman-core/src/web3/wallet/program/mod.rs b/crates/openhuman-core/src/web3/wallet/program/mod.rs index 49786267773..b0caec44c63 100644 --- a/crates/openhuman-core/src/web3/wallet/program/mod.rs +++ b/crates/openhuman-core/src/web3/wallet/program/mod.rs @@ -384,14 +384,12 @@ pub fn summarize( *total = total.saturating_add(amount); movements.push(movement); } - ASSOCIATED_TOKEN_PROGRAM => { - // Create (empty data or 0) and CreateIdempotent (1) only; - // RecoverNested moves tokens. - if !matches!(instruction.data.as_slice(), [] | [0] | [1]) { - return Err(forbidden(format!( - "instruction {position} is not an associated token account create" - ))); - } + // Create (empty data or 0) and CreateIdempotent (1) only; + // RecoverNested moves tokens. + ASSOCIATED_TOKEN_PROGRAM if !matches!(instruction.data.as_slice(), [] | [0] | [1]) => { + return Err(forbidden(format!( + "instruction {position} is not an associated token account create" + ))); } _ => {} } From a648b83921ddf63a88d9fe05d3d9314014b2f9d3 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Sun, 15 Nov 2026 22:07:45 +0000 Subject: [PATCH 21/32] refactor(wallet): move program controller schemas into program module The account, prepare_program and execute_prepared_program controller registrations and schemas now live in the program submodule and are merged into the wallet controller list at runtime, keeping the program-specific definitions next to the code they describe. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../src/web3/wallet/program/mod.rs | 1 + .../src/web3/wallet/program/schemas.rs | 134 ++++++++++++++++++ .../openhuman-core/src/web3/wallet/schemas.rs | 109 +------------- 3 files changed, 142 insertions(+), 102 deletions(-) create mode 100644 crates/openhuman-core/src/web3/wallet/program/schemas.rs diff --git a/crates/openhuman-core/src/web3/wallet/program/mod.rs b/crates/openhuman-core/src/web3/wallet/program/mod.rs index b0caec44c63..063a3e135ea 100644 --- a/crates/openhuman-core/src/web3/wallet/program/mod.rs +++ b/crates/openhuman-core/src/web3/wallet/program/mod.rs @@ -543,6 +543,7 @@ pub fn evaluate_program( } mod ops; +pub(crate) mod schemas; pub use ops::{ execute_prepared_program, prepare_program, ExecuteProgramParams, ExecutedProgram, PrepareProgramParams, PreparedProgram, diff --git a/crates/openhuman-core/src/web3/wallet/program/schemas.rs b/crates/openhuman-core/src/web3/wallet/program/schemas.rs new file mode 100644 index 00000000000..a036d199d68 --- /dev/null +++ b/crates/openhuman-core/src/web3/wallet/program/schemas.rs @@ -0,0 +1,134 @@ +//! Controller schemas and handlers for `wallet.account`, +//! `wallet.prepare_program` and `wallet.execute_prepared_program`. + +use serde::Deserialize; +use serde_json::{Map, Value}; + +use crate::core::all::{ControllerFuture, RegisteredController}; +use crate::core::runtime::DispatchCtx; +use crate::core::{ControllerSchema, FieldSchema, TypeSchema}; + +use super::super::ops::WalletChain; + +fn required_json(name: &'static str, comment: &'static str) -> FieldSchema { + FieldSchema { + name, + ty: TypeSchema::Json, + comment, + required: true, + } +} + +/// The registered controllers of this module. +pub(crate) fn registered() -> Vec { + vec![ + RegisteredController { + schema: schema("account"), + handler: handle_account, + }, + RegisteredController { + schema: schema("prepare_program"), + handler: handle_prepare_program, + }, + RegisteredController { + schema: schema("execute_prepared_program"), + handler: handle_execute_prepared_program, + }, + ] +} + +/// The schema of one of this module's controllers. +pub(crate) fn schema(function: &str) -> ControllerSchema { + match function { + "account" => ControllerSchema { + namespace: "wallet", + function: "account", + description: "Read one wallet account by chain and index. A known secondary account (Solana index 1, m/44'/501'/1'/0', label giveaway) that this wallet's stored state predates is derived from the encrypted recovery phrase and stored first.", + inputs: vec![ + required_json("chain", "Chain family (evm | btc | solana | tron)."), + required_json("accountIndex", "Account index on the chain; 0 is the primary account."), + ], + outputs: vec![FieldSchema { + name: "result", + ty: TypeSchema::Json, + comment: "{chain, address, derivationPath, index?, label?}.", + required: true, + }], + }, + "prepare_program" => ControllerSchema { + namespace: "wallet", + function: "prepare_program", + description: "Check a host-built unsigned Solana transaction against [wallet_policy.accounts.solana_] and hold it as a quote for 60 seconds. Refused (WALLET_POLICY_REFUSED:) unless the account has a section, is the fee payer and only signer, every instruction invokes an allowed program, token instructions are TransferChecked of one listed mint within its per-transaction and rolling 24h caps, ATA instructions are creates, and there is no System program instruction or address lookup table.", + inputs: vec![ + required_json("accountIndex", "Index of the Solana account that signs (1 is m/44'/501'/1'/0')."), + required_json("transaction", "Base64 of the unsigned transaction's wire bytes (legacy or v0, signature slots zeroed)."), + ], + outputs: vec![FieldSchema { + name: "result", + ty: TypeSchema::Json, + comment: "{quoteId, chain, accountIndex, address, createdAtMs, expiresAtMs, summary: {feePayer, recentBlockhash, programs, instructions: [{programId, accounts, dataHex}], movements: [{programId, mint, source, destination, authority, amountRaw, decimals}], totals: [{mint, amountRaw}]}}.", + required: true, + }], + }, + "execute_prepared_program" => ControllerSchema { + namespace: "wallet", + function: "execute_prepared_program", + description: "Sign a prepared program transaction with the account's key inside the wallet module and send it to the Solana RPC. The policy is re-checked and the spend reserved in the ledger first; the attempt is recorded broadcast or in_doubt and a quote is never executed twice.", + inputs: vec![ + required_json("accountIndex", "The account index the quote was prepared for."), + required_json("quoteId", "quoteId returned by wallet.prepare_program."), + ], + outputs: vec![FieldSchema { + name: "result", + ty: TypeSchema::Json, + comment: "{quoteId, chain, accountIndex, address, transactionHash}.", + required: true, + }], + }, + _ => unreachable!("not a program controller: {function}"), + } +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct AccountParams { + chain: WalletChain, + #[serde(alias = "account_index")] + account_index: u32, +} + +pub(crate) fn handle_account(ctx: DispatchCtx, params: Map) -> ControllerFuture { + Box::pin(async move { + let parsed: AccountParams = serde_json::from_value(Value::Object(params)) + .map_err(|e| format!("invalid params: {e}"))?; + let account = + crate::web3::wallet::ensure_account(&ctx, parsed.chain, parsed.account_index).await?; + serde_json::to_value(account).map_err(|e| format!("failed to encode account: {e}")) + }) +} + +pub(crate) fn handle_prepare_program( + ctx: DispatchCtx, + params: Map, +) -> ControllerFuture { + Box::pin(async move { + let parsed: super::PrepareProgramParams = serde_json::from_value(Value::Object(params)) + .map_err(|e| format!("invalid params: {e}"))?; + super::prepare_program(&ctx, parsed) + .await? + .into_cli_compatible_json() + }) +} + +pub(crate) fn handle_execute_prepared_program( + ctx: DispatchCtx, + params: Map, +) -> ControllerFuture { + Box::pin(async move { + let parsed: super::ExecuteProgramParams = serde_json::from_value(Value::Object(params)) + .map_err(|e| format!("invalid params: {e}"))?; + super::execute_prepared_program(&ctx, parsed) + .await? + .into_cli_compatible_json() + }) +} diff --git a/crates/openhuman-core/src/web3/wallet/schemas.rs b/crates/openhuman-core/src/web3/wallet/schemas.rs index 3838bb40475..3833557f533 100644 --- a/crates/openhuman-core/src/web3/wallet/schemas.rs +++ b/crates/openhuman-core/src/web3/wallet/schemas.rs @@ -97,7 +97,7 @@ pub fn all_wallet_controller_schemas() -> Vec { } pub fn all_wallet_registered_controllers() -> Vec { - vec![ + let mut controllers = vec![ RegisteredController { schema: wallet_schemas("status"), handler: handle_status, @@ -178,19 +178,9 @@ pub fn all_wallet_registered_controllers() -> Vec { schema: wallet_schemas("ledger_list"), handler: handle_ledger_list, }, - RegisteredController { - schema: wallet_schemas("account"), - handler: handle_account, - }, - RegisteredController { - schema: wallet_schemas("prepare_program"), - handler: handle_prepare_program, - }, - RegisteredController { - schema: wallet_schemas("execute_prepared_program"), - handler: handle_execute_prepared_program, - }, - ] + ]; + controllers.extend(super::program::schemas::registered()); + controllers } pub fn wallet_schemas(function: &str) -> ControllerSchema { @@ -501,51 +491,9 @@ pub fn wallet_schemas(function: &str) -> ControllerSchema { required: true, }], }, - "account" => ControllerSchema { - namespace: "wallet", - function: "account", - description: "Read one wallet account by chain and index. A known secondary account (Solana index 1, m/44'/501'/1'/0', label giveaway) that this wallet's stored state predates is derived from the encrypted recovery phrase and stored first.", - inputs: vec![ - required_json("chain", "Chain family (evm | btc | solana | tron)."), - required_json("accountIndex", "Account index on the chain; 0 is the primary account."), - ], - outputs: vec![FieldSchema { - name: "result", - ty: TypeSchema::Json, - comment: "{chain, address, derivationPath, index?, label?}.", - required: true, - }], - }, - "prepare_program" => ControllerSchema { - namespace: "wallet", - function: "prepare_program", - description: "Check a host-built unsigned Solana transaction against [wallet_policy.accounts.solana_] and hold it as a quote for 60 seconds. Refused (WALLET_POLICY_REFUSED:) unless the account has a section, is the fee payer and only signer, every instruction invokes an allowed program, token instructions are TransferChecked of one listed mint within its per-transaction and rolling 24h caps, ATA instructions are creates, and there is no System program instruction or address lookup table.", - inputs: vec![ - required_json("accountIndex", "Index of the Solana account that signs (1 is m/44'/501'/1'/0')."), - required_json("transaction", "Base64 of the unsigned transaction's wire bytes (legacy or v0, signature slots zeroed)."), - ], - outputs: vec![FieldSchema { - name: "result", - ty: TypeSchema::Json, - comment: "{quoteId, chain, accountIndex, address, createdAtMs, expiresAtMs, summary: {feePayer, recentBlockhash, programs, instructions: [{programId, accounts, dataHex}], movements: [{programId, mint, source, destination, authority, amountRaw, decimals}], totals: [{mint, amountRaw}]}}.", - required: true, - }], - }, - "execute_prepared_program" => ControllerSchema { - namespace: "wallet", - function: "execute_prepared_program", - description: "Sign a prepared program transaction with the account's key inside the wallet module and send it to the Solana RPC. The policy is re-checked and the spend reserved in the ledger first; the attempt is recorded broadcast or in_doubt and a quote is never executed twice.", - inputs: vec![ - required_json("accountIndex", "The account index the quote was prepared for."), - required_json("quoteId", "quoteId returned by wallet.prepare_program."), - ], - outputs: vec![FieldSchema { - name: "result", - ty: TypeSchema::Json, - comment: "{quoteId, chain, accountIndex, address, transactionHash}.", - required: true, - }], - }, + "account" | "prepare_program" | "execute_prepared_program" => { + super::program::schemas::schema(function) + } _ => ControllerSchema { namespace: "wallet", function: "unknown", @@ -756,49 +704,6 @@ fn handle_ledger_list(ctx: DispatchCtx, params: Map) -> Controlle }) } -#[derive(Debug, Deserialize)] -#[serde(rename_all = "camelCase", deny_unknown_fields)] -struct AccountParams { - chain: WalletChain, - #[serde(alias = "account_index")] - account_index: u32, -} - -fn handle_account(ctx: DispatchCtx, params: Map) -> ControllerFuture { - Box::pin(async move { - let parsed: AccountParams = serde_json::from_value(Value::Object(params)) - .map_err(|e| format!("invalid params: {e}"))?; - let account = - crate::web3::wallet::ensure_account(&ctx, parsed.chain, parsed.account_index).await?; - serde_json::to_value(account).map_err(|e| format!("failed to encode account: {e}")) - }) -} - -fn handle_prepare_program(ctx: DispatchCtx, params: Map) -> ControllerFuture { - Box::pin(async move { - let parsed: super::program::PrepareProgramParams = - serde_json::from_value(Value::Object(params)) - .map_err(|e| format!("invalid params: {e}"))?; - super::program::prepare_program(&ctx, parsed) - .await? - .into_cli_compatible_json() - }) -} - -fn handle_execute_prepared_program( - ctx: DispatchCtx, - params: Map, -) -> ControllerFuture { - Box::pin(async move { - let parsed: super::program::ExecuteProgramParams = - serde_json::from_value(Value::Object(params)) - .map_err(|e| format!("invalid params: {e}"))?; - super::program::execute_prepared_program(&ctx, parsed) - .await? - .into_cli_compatible_json() - }) -} - /// Shared input schema for the tx_status / tx_receipt / lookup_tx readers. fn tx_query_inputs() -> Vec { vec![ From 9f0536222e7006ed347d79994a462b54f3b80372 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Sun, 15 Nov 2026 22:08:48 +0000 Subject: [PATCH 22/32] feat(wallet): validate declared token debits against transaction transfers Program executes now take the caller's declared per-mint debits and reject any transaction whose visible transfers exceed them, adding a SimulationMismatch refusal kind for the case. Caps and the single-mint limit apply to the declared debits rather than the transaction's totals, so zero debits are ignored and CPI-driven movements are left to simulation. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../openhuman-core/src/web3/wallet/policy.rs | 3 + .../src/web3/wallet/program/mod.rs | 72 +++++++++++++++++-- 2 files changed, 69 insertions(+), 6 deletions(-) diff --git a/crates/openhuman-core/src/web3/wallet/policy.rs b/crates/openhuman-core/src/web3/wallet/policy.rs index 1a499b0b5d9..7069f20e292 100644 --- a/crates/openhuman-core/src/web3/wallet/policy.rs +++ b/crates/openhuman-core/src/web3/wallet/policy.rs @@ -162,6 +162,9 @@ pub enum RefusalKind { /// The transaction itself cannot be signed by this account (wrong fee /// payer, extra signers, address lookup tables, malformed bytes). TransactionNotAllowed, + /// The declared token debits disagree with what the transaction moves + /// (its visible transfers, or its simulation), or the simulation failed. + SimulationMismatch, } /// A refused execute. diff --git a/crates/openhuman-core/src/web3/wallet/program/mod.rs b/crates/openhuman-core/src/web3/wallet/program/mod.rs index 063a3e135ea..89de509eaf6 100644 --- a/crates/openhuman-core/src/web3/wallet/program/mod.rs +++ b/crates/openhuman-core/src/web3/wallet/program/mod.rs @@ -460,8 +460,64 @@ fn token_transfer_checked( // ── Policy ────────────────────────────────────────────────────────────────── +/// Check the caller's declared debits against what the transaction visibly +/// moves: one entry per mint, each a whole number, and every mint a top-level +/// `TransferChecked` moves declared with at least that amount. Programs that +/// move tokens by CPI (a distributor funding its vault) are invisible here; +/// simulation ([`simulate::check_simulation`]) holds the declaration to what +/// the account's balances actually lose. +/// +/// # Errors +/// +/// The refusal. +pub fn check_declared( + summary: &ProgramTransactionSummary, + declared: &[MintTotal], +) -> Result<(), PolicyRefusal> { + let mut seen: Vec<&str> = Vec::new(); + for debit in declared { + if seen.contains(&debit.mint.as_str()) { + return Err(structural(format!("mint {} is declared twice", debit.mint))); + } + seen.push(&debit.mint); + if debit.amount_raw.trim().parse::().is_err() { + return Err(structural(format!( + "the declared amount of mint {} is not a whole number of atomic units", + debit.mint + ))); + } + } + for total in &summary.totals { + let visible: u128 = total.amount_raw.parse().unwrap_or(u128::MAX); + let stated = declared + .iter() + .find(|debit| debit.mint == total.mint) + .map_or(0, |debit| debit.amount()); + if stated < visible { + return Err(refusal( + RefusalKind::SimulationMismatch, + format!( + "the transaction transfers {visible} of mint {} but declares {stated}", + total.mint + ), + )); + } + } + Ok(()) +} + +impl MintTotal { + /// The amount as an integer; unparseable reads as the maximum. + #[must_use] + pub fn amount(&self) -> u128 { + self.amount_raw.trim().parse().unwrap_or(u128::MAX) + } +} + /// Decide whether `chain`'s account `account_index` may sign a transaction -/// with `summary`, given the ledger `records`. +/// with `summary` that debits `declared` from the account, given the ledger +/// `records`. Caps apply to the declared debits (which simulation then +/// holds the transaction to); zero debits are ignored. /// /// # Errors /// @@ -471,6 +527,7 @@ pub fn evaluate_program( chain: &str, account_index: u32, summary: &ProgramTransactionSummary, + declared: &[MintTotal], records: &[LedgerRecord], now_ms: u64, ) -> Result<(), PolicyRefusal> { @@ -492,13 +549,15 @@ pub fn evaluate_program( format!("program {program} is not in {key}'s allowed_programs"), )); } - if summary.totals.len() > 1 { + check_declared(summary, declared)?; + let debits: Vec<&MintTotal> = declared.iter().filter(|debit| debit.amount() > 0).collect(); + if debits.len() > 1 { return Err(structural(format!( - "the transaction moves {} mints; a program execute may move at most one", - summary.totals.len() + "the transaction debits {} mints; a program execute may move at most one", + debits.len() ))); } - let Some(total) = summary.totals.first() else { + let Some(total) = debits.first() else { return Ok(()); }; let Some(cap) = section.mints.iter().find(|cap| cap.mint == total.mint) else { @@ -507,7 +566,7 @@ pub fn evaluate_program( format!("mint {} is not in {key}'s mints", total.mint), )); }; - let amount: u128 = total.amount_raw.parse().unwrap_or(u128::MAX); + let amount = total.amount(); if amount > u128::from(cap.per_tx_max_raw) { return Err(refusal( RefusalKind::PerTransaction, @@ -544,6 +603,7 @@ pub fn evaluate_program( mod ops; pub(crate) mod schemas; +pub mod simulate; pub use ops::{ execute_prepared_program, prepare_program, ExecuteProgramParams, ExecutedProgram, PrepareProgramParams, PreparedProgram, From e8cfa496f3029f72f0f92e90d22564d6d42f3694 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Sun, 15 Nov 2026 22:09:18 +0000 Subject: [PATCH 23/32] feat(web3): add program simulation for wallet transactions Introduce a simulation helper that runs wallet program instructions before submission so callers can preview outcomes and catch failures early. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../src/web3/wallet/program/simulate.rs | 247 ++++++++++++++++++ 1 file changed, 247 insertions(+) create mode 100644 crates/openhuman-core/src/web3/wallet/program/simulate.rs diff --git a/crates/openhuman-core/src/web3/wallet/program/simulate.rs b/crates/openhuman-core/src/web3/wallet/program/simulate.rs new file mode 100644 index 00000000000..117f86f5493 --- /dev/null +++ b/crates/openhuman-core/src/web3/wallet/program/simulate.rs @@ -0,0 +1,247 @@ +//! Simulate a program transaction and measure what it debits from the +//! signing account's token balances. +//! +//! A program that moves tokens by CPI (a distributor funding its vault from +//! the signer's token account) shows no amount in its outer instruction, so +//! the caller declares the debit and the host holds the transaction to it: +//! +//! 1. `getTokenAccountsByOwner` for the signer, under SPL Token and +//! Token-2022, gives every token account it owns and its balance now. +//! 2. `simulateTransaction` (no signature check, the transaction's own +//! blockhash) returns those accounts' post-transaction state. +//! 3. The debit of each mint is the drop in the sum of those balances. An +//! account that the transaction closes, or whose owner it changes, counts +//! as emptied. Credits are ignored. +//! +//! [`check_simulation`] then refuses unless the simulation succeeded and every +//! mint's debit equals the declared amount (undeclared mints: zero). Native +//! SOL spent on fees and rent is not measured here. + +use std::collections::BTreeMap; + +use base64::Engine as _; +use serde::{Deserialize, Serialize}; +use serde_json::{json, Value}; + +use super::super::policy::{refusal, PolicyRefusal, RefusalKind}; +use super::{base58, MintTotal, TOKEN_2022_PROGRAM, TOKEN_PROGRAM}; + +/// Size of the base token-account layout shared by SPL Token and Token-2022. +const TOKEN_ACCOUNT_LEN: usize = 165; + +/// What the simulation showed. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct SimulationReport { + /// The simulation error, if the transaction would fail. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub err: Option, + /// Per-mint debits of the signer's token accounts, non-zero only. + pub debits: Vec, + /// The signer's token accounts the simulation read. + pub token_accounts: Vec, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub units_consumed: Option, +} + +/// A token account's mint, owner and balance. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct TokenAccountState { + pub mint: [u8; 32], + pub owner: [u8; 32], + pub amount: u64, +} + +/// Parse the base layout of an SPL Token or Token-2022 account. +#[must_use] +pub fn parse_token_account(data: &[u8]) -> Option { + if data.len() < TOKEN_ACCOUNT_LEN { + return None; + } + let mut mint = [0u8; 32]; + mint.copy_from_slice(&data[..32]); + let mut owner = [0u8; 32]; + owner.copy_from_slice(&data[32..64]); + let mut amount = [0u8; 8]; + amount.copy_from_slice(&data[64..72]); + Some(TokenAccountState { + mint, + owner, + amount: u64::from_le_bytes(amount), + }) +} + +/// Per-mint debits: for each pre-state account the signer owns, its balance +/// minus its post-state balance (zero when closed or no longer the signer's). +#[must_use] +pub fn debits( + owner: &[u8; 32], + pre: &[TokenAccountState], + post: &[Option], +) -> Vec { + let mut by_mint: BTreeMap<[u8; 32], (u128, u128)> = BTreeMap::new(); + for (index, before) in pre.iter().enumerate() { + if before.owner != *owner { + continue; + } + let after = post + .get(index) + .copied() + .flatten() + .filter(|after| after.owner == *owner && after.mint == before.mint) + .map_or(0, |after| after.amount); + let entry = by_mint.entry(before.mint).or_default(); + entry.0 += u128::from(before.amount); + entry.1 += u128::from(after); + } + by_mint + .into_iter() + .filter(|(_, (before, after))| before > after) + .map(|(mint, (before, after))| MintTotal { + mint: base58(&mint), + amount_raw: (before - after).to_string(), + }) + .collect() +} + +/// Refuse unless the simulation succeeded and every debit equals `declared`. +/// +/// # Errors +/// +/// The refusal. +pub fn check_simulation( + declared: &[MintTotal], + report: &SimulationReport, +) -> Result<(), PolicyRefusal> { + if let Some(err) = &report.err { + return Err(refusal( + RefusalKind::SimulationMismatch, + format!("the transaction fails in simulation: {err}"), + )); + } + let mut mints: Vec<&str> = declared.iter().map(|d| d.mint.as_str()).collect(); + for debit in &report.debits { + if !mints.contains(&debit.mint.as_str()) { + mints.push(&debit.mint); + } + } + for mint in mints { + let stated = declared + .iter() + .find(|d| d.mint == mint) + .map_or(0, MintTotal::amount); + let simulated = report + .debits + .iter() + .find(|d| d.mint == mint) + .map_or(0, MintTotal::amount); + if stated != simulated { + return Err(refusal( + RefusalKind::SimulationMismatch, + format!( + "the simulation debits {simulated} of mint {mint} from the account, \ + but {stated} was declared" + ), + )); + } + } + Ok(()) +} + +fn account_data(account: &Value) -> Option> { + let encoded = account.get("data")?.get(0)?.as_str()?; + base64::engine::general_purpose::STANDARD + .decode(encoded) + .ok() +} + +/// Read the signer's token accounts, simulate `transaction` and measure the +/// debits, over the Solana JSON-RPC at `url`. +/// +/// # Errors +/// +/// A transport or RPC error, or an answer that is not the documented shape. +pub async fn simulate( + url: &str, + transaction: &[u8], + owner: &[u8; 32], +) -> Result { + let owner_text = base58(owner); + let mut addresses = Vec::new(); + let mut pre = Vec::new(); + for program in [TOKEN_PROGRAM, TOKEN_2022_PROGRAM] { + let answer: Value = super::super::rpc::rpc_call_to( + url, + "getTokenAccountsByOwner", + json!([ + owner_text, + {"programId": program}, + {"encoding": "base64", "commitment": "confirmed"} + ]), + ) + .await?; + let rows = answer + .get("value") + .and_then(Value::as_array) + .ok_or("getTokenAccountsByOwner returned no value list")?; + for row in rows { + let pubkey = row + .get("pubkey") + .and_then(Value::as_str) + .ok_or("getTokenAccountsByOwner row has no pubkey")?; + let state = row + .get("account") + .and_then(account_data) + .and_then(|data| parse_token_account(&data)) + .ok_or("getTokenAccountsByOwner row is not a token account")?; + addresses.push(pubkey.to_string()); + pre.push(state); + } + } + let encoded = base64::engine::general_purpose::STANDARD.encode(transaction); + let answer: Value = super::super::rpc::rpc_call_to( + url, + "simulateTransaction", + json!([ + encoded, + { + "encoding": "base64", + "sigVerify": false, + "replaceRecentBlockhash": false, + "commitment": "confirmed", + "accounts": {"encoding": "base64", "addresses": addresses} + } + ]), + ) + .await?; + let value = answer + .get("value") + .ok_or("simulateTransaction returned no value")?; + let err = value.get("err").filter(|err| !err.is_null()).cloned(); + let post: Vec> = match value.get("accounts").and_then(Value::as_array) + { + Some(accounts) => accounts + .iter() + .map(|account| account_data(account).and_then(|data| parse_token_account(&data))) + .collect(), + None if err.is_some() => Vec::new(), + None => return Err("simulateTransaction returned no accounts".to_string()), + }; + if err.is_none() && post.len() != pre.len() { + return Err("simulateTransaction returned the wrong number of accounts".to_string()); + } + Ok(SimulationReport { + debits: if err.is_some() { + Vec::new() + } else { + debits(owner, &pre, &post) + }, + err, + token_accounts: addresses, + units_consumed: value.get("unitsConsumed").and_then(Value::as_u64), + }) +} + +#[cfg(test)] +#[path = "simulate_tests.rs"] +mod tests; From 96140f3012e1bab16743d9b09391ecd8fa108fac Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Sun, 15 Nov 2026 22:10:32 +0000 Subject: [PATCH 24/32] feat(wallet): simulate program transactions before quoting and executing Program quotes now require the caller to declare the token debits the transaction should make, and the transaction is simulated against the Solana endpoint to confirm those debits match before a quote is issued. Execution re-simulates against current chain state so the declared debits and caps still hold when the key is used, and ledger records now derive their total from the declared debits rather than the summary. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../src/web3/wallet/program/ops.rs | 60 +++++++++++++++++-- .../src/web3/wallet/program/schemas.rs | 7 ++- .../src/web3/wallet/schemas_tests.rs | 2 +- 3 files changed, 59 insertions(+), 10 deletions(-) diff --git a/crates/openhuman-core/src/web3/wallet/program/ops.rs b/crates/openhuman-core/src/web3/wallet/program/ops.rs index 4a9dc39ca2b..e8dc1f3fe2f 100644 --- a/crates/openhuman-core/src/web3/wallet/program/ops.rs +++ b/crates/openhuman-core/src/web3/wallet/program/ops.rs @@ -16,9 +16,11 @@ use crate::core::Outcome; use super::super::ledger::{LedgerKind, LedgerRecord, LedgerStatus, SpendLedger}; use super::super::ops::WalletChain; -use super::super::policy::{origin_refusal, refusal, ExecutionOrigin, RefusalKind}; +use super::super::policy::{origin_refusal, refusal, ExecutionOrigin, PolicyRefusal, RefusalKind}; +use super::simulate::{check_simulation, simulate, SimulationReport}; use super::{ attach_signature, base58, decode_transaction, evaluate_program, summarize, DecodedTransaction, + MintTotal, ProgramTransactionSummary, LOG_PREFIX, QUOTE_PREFIX, QUOTE_TTL_MS, }; @@ -34,6 +36,10 @@ pub struct PreparedProgram { /// The signing account's address (the fee payer). pub address: String, pub summary: ProgramTransactionSummary, + /// The token debits the caller declared, which the caps were applied to. + pub declared_debits: Vec, + /// The simulation that confirmed them. + pub simulation: SimulationReport, pub created_at_ms: u64, pub expires_at_ms: u64, } @@ -59,6 +65,11 @@ pub struct PrepareProgramParams { /// Base64 of the unsigned transaction's wire bytes (signature slots /// zeroed), e.g. `transaction.serialize({requireAllSignatures: false})`. pub transaction: String, + /// What the transaction debits from the account's token balances, per + /// mint (`[{mint, amountRaw}]`, empty when it debits nothing). The caps + /// apply to these amounts, and the simulation must debit exactly them. + #[serde(alias = "expected_debits")] + pub expected_debits: Vec, } /// `wallet.execute_prepared_program` parameters. @@ -147,24 +158,30 @@ pub async fn prepare_program( let summary = summarize(&decoded, &account.address).map_err(|refused| refused.to_string())?; let now = super::super::policy::wall_clock_ms(); let (_, records) = ledger_records(&config)?; + let refused = |refused: PolicyRefusal| { + tracing::info!(account = %key, kind = ?refused.kind, "{LOG_PREFIX} prepare refused"); + refused.to_string() + }; evaluate_program( &config.wallet_policy, chain_name(chain), params.account_index, &summary, + ¶ms.expected_debits, &records, now, ) - .map_err(|refused| { - tracing::info!(account = %key, kind = ?refused.kind, "{LOG_PREFIX} prepare refused"); - refused.to_string() - })?; + .map_err(refused)?; + let simulation = simulate_quote(ctx, &transaction, &decoded).await?; + check_simulation(¶ms.expected_debits, &simulation).map_err(refused)?; let prepared = PreparedProgram { quote_id: format!("{QUOTE_PREFIX}{}", uuid::Uuid::new_v4()), chain, account_index: params.account_index, address: account.address, summary, + declared_debits: params.expected_debits, + simulation, created_at_ms: now, expires_at_ms: now + QUOTE_TTL_MS, }; @@ -196,7 +213,10 @@ pub(crate) fn program_record( status: LedgerStatus, now_ms: u64, ) -> LedgerRecord { - let total = prepared.summary.totals.first(); + let total = prepared + .declared_debits + .iter() + .find(|debit| debit.amount() > 0); let destination = match prepared.summary.movements.as_slice() { [] => String::new(), [only] => only.destination.clone(), @@ -257,11 +277,21 @@ pub async fn execute_prepared_program( let prepared = stored.prepared.clone(); let chain = chain_name(prepared.chain); let (ledger, _) = ledger_records(&config)?; + // Simulate again against the chain as it is now: the caps and the + // declaration must still hold when the key is used. + let simulated = match simulate_quote(ctx, &stored.transaction, &stored.decoded).await { + Ok(report) => check_simulation(&prepared.declared_debits, &report), + Err(error) => { + store_quote(stored, now); + return Err(error); + } + }; let reserved = ledger .reserve(|records| { if let Some(refused) = origin_refusal(&origin) { return Err(refused); } + simulated.clone()?; if let Some(earlier) = records.iter().rev().find(|record| { record.quote_id == prepared.quote_id && record.status.counts_against_caps() }) { @@ -278,6 +308,7 @@ pub async fn execute_prepared_program( chain, prepared.account_index, &prepared.summary, + &prepared.declared_debits, records, now, )?; @@ -409,3 +440,20 @@ async fn solana_rpc_url(ctx: &DispatchCtx) -> Result { .map(|row| row.rpc_url) .ok_or_else(|| "the wallet module reports no default Solana endpoint".to_string()) } + +/// Simulate `transaction` against the configured Solana endpoint and measure +/// the fee payer's token debits. +async fn simulate_quote( + ctx: &DispatchCtx, + transaction: &[u8], + decoded: &DecodedTransaction, +) -> Result { + let owner = decoded + .account_keys + .first() + .ok_or_else(|| "the transaction lists no accounts".to_string())?; + let url = solana_rpc_url(ctx).await?; + simulate(&url, transaction, owner) + .await + .map_err(|error| format!("could not simulate the transaction: {error}")) +} diff --git a/crates/openhuman-core/src/web3/wallet/program/schemas.rs b/crates/openhuman-core/src/web3/wallet/program/schemas.rs index a036d199d68..27a6a14550e 100644 --- a/crates/openhuman-core/src/web3/wallet/program/schemas.rs +++ b/crates/openhuman-core/src/web3/wallet/program/schemas.rs @@ -58,22 +58,23 @@ pub(crate) fn schema(function: &str) -> ControllerSchema { "prepare_program" => ControllerSchema { namespace: "wallet", function: "prepare_program", - description: "Check a host-built unsigned Solana transaction against [wallet_policy.accounts.solana_] and hold it as a quote for 60 seconds. Refused (WALLET_POLICY_REFUSED:) unless the account has a section, is the fee payer and only signer, every instruction invokes an allowed program, token instructions are TransferChecked of one listed mint within its per-transaction and rolling 24h caps, ATA instructions are creates, and there is no System program instruction or address lookup table.", + description: "Check a host-built unsigned Solana transaction against [wallet_policy.accounts.solana_] and hold it as a quote for 60 seconds. Refused (WALLET_POLICY_REFUSED:) unless the account has a section, is the fee payer and only signer, every instruction invokes an allowed program, token instructions (SPL Token or Token-2022) are TransferChecked, the declared expectedDebits cover them and name at most one listed mint within its per-transaction and rolling 24h caps, ATA instructions are creates, there is no System program instruction or address lookup table, and simulateTransaction succeeds and debits the account's token accounts by exactly expectedDebits.", inputs: vec![ required_json("accountIndex", "Index of the Solana account that signs (1 is m/44'/501'/1'/0')."), required_json("transaction", "Base64 of the unsigned transaction's wire bytes (legacy or v0, signature slots zeroed)."), + required_json("expectedDebits", "Array of {mint, amountRaw}: what the transaction debits from the account's token balances (SPL Token or Token-2022), per mint; [] when nothing. Caps apply to these amounts and the simulation must debit exactly them."), ], outputs: vec![FieldSchema { name: "result", ty: TypeSchema::Json, - comment: "{quoteId, chain, accountIndex, address, createdAtMs, expiresAtMs, summary: {feePayer, recentBlockhash, programs, instructions: [{programId, accounts, dataHex}], movements: [{programId, mint, source, destination, authority, amountRaw, decimals}], totals: [{mint, amountRaw}]}}.", + comment: "{quoteId, chain, accountIndex, address, createdAtMs, expiresAtMs, declaredDebits: [{mint, amountRaw}], simulation: {err?, debits: [{mint, amountRaw}], tokenAccounts, unitsConsumed?}, summary: {feePayer, recentBlockhash, programs, instructions: [{programId, accounts, dataHex}], movements: [{programId, mint, source, destination, authority, amountRaw, decimals}], totals: [{mint, amountRaw}]}}.", required: true, }], }, "execute_prepared_program" => ControllerSchema { namespace: "wallet", function: "execute_prepared_program", - description: "Sign a prepared program transaction with the account's key inside the wallet module and send it to the Solana RPC. The policy is re-checked and the spend reserved in the ledger first; the attempt is recorded broadcast or in_doubt and a quote is never executed twice.", + description: "Sign a prepared program transaction with the account's key inside the wallet module and send it to the Solana RPC. The transaction is simulated again and the policy re-checked, and the spend reserved in the ledger first; the attempt is recorded broadcast or in_doubt and a quote is never executed twice.", inputs: vec![ required_json("accountIndex", "The account index the quote was prepared for."), required_json("quoteId", "quoteId returned by wallet.prepare_program."), diff --git a/crates/openhuman-core/src/web3/wallet/schemas_tests.rs b/crates/openhuman-core/src/web3/wallet/schemas_tests.rs index 2c853a8687e..1cec42309fa 100644 --- a/crates/openhuman-core/src/web3/wallet/schemas_tests.rs +++ b/crates/openhuman-core/src/web3/wallet/schemas_tests.rs @@ -21,7 +21,7 @@ fn wallet_schema_wire_contracts_are_preserved() { ("tx_status", &["chain", "hash", "evmNetwork"][..]), ("execute_prepared", &["quoteId", "confirmed"][..]), ("account", &["chain", "accountIndex"][..]), - ("prepare_program", &["accountIndex", "transaction"][..]), + ("prepare_program", &["accountIndex", "transaction", "expectedDebits"][..]), ("execute_prepared_program", &["accountIndex", "quoteId"][..]), ] { let schema = wallet_schemas(function); From 209d0c29b2d1618ddc8c6a655ebefae830b32d5c Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Sun, 15 Nov 2026 22:10:54 +0000 Subject: [PATCH 25/32] test(web3): update wallet program tests for token-2022 and simulation Switch the test fixtures to a Token-2022 mint and the real rewards program address instead of synthetic keys, and pass declared debits and simulation reports through the new evaluate_program signature. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../src/web3/wallet/program/mod_tests.rs | 70 ++++++++----------- 1 file changed, 30 insertions(+), 40 deletions(-) diff --git a/crates/openhuman-core/src/web3/wallet/program/mod_tests.rs b/crates/openhuman-core/src/web3/wallet/program/mod_tests.rs index 355faaca91e..a63b0ac8d86 100644 --- a/crates/openhuman-core/src/web3/wallet/program/mod_tests.rs +++ b/crates/openhuman-core/src/web3/wallet/program/mod_tests.rs @@ -5,6 +5,7 @@ use crate::web3::wallet::ledger::LedgerStatus; use crate::web3::wallet::ops::WalletChain; use crate::web3::wallet::policy::ExecutionOrigin; use base64::Engine as _; +use simulate::SimulationReport; /// `m/44'/501'/1'/0'` of the BIP-39 test phrase (see `ops_tests.rs`). const SIGNER: &str = "Hh8QwFUA6MtVu1qAoq12ucvFHNwCcVTV7hpWjeY1Hztb"; @@ -19,8 +20,13 @@ fn filled(byte: u8) -> [u8; 32] { [byte; 32] } +/// $TINY, a Token-2022 mint with 6 decimals. +const TINY_MINT: &str = "2AF7CqwieUjUPALL7icuZtL3X7wENdjUjGBMmfV2pump"; +/// The Solana Foundation Rewards (merkle distributor) program. +const REWARDS_PROGRAM: &str = "REWArDioXgQJ2fZKkfu9LCLjQfRwYWVVfsvcsR5hoXi"; + fn mint() -> String { - base58(&filled(7)) + TINY_MINT.to_string() } fn other_mint() -> String { @@ -115,7 +121,7 @@ fn transfer_checked(mint: &str, amount: u64) -> Ix { data.extend(amount.to_le_bytes()); data.push(6); Ix { - program: key(TOKEN_PROGRAM), + program: key(TOKEN_2022_PROGRAM), accounts: vec![filled(1), key(mint), filled(2), key(SIGNER)], data, } @@ -123,7 +129,7 @@ fn transfer_checked(mint: &str, amount: u64) -> Ix { fn distributor_call() -> Ix { Ix { - program: filled(11), + program: key(REWARDS_PROGRAM), accounts: vec![filled(3), key(SIGNER)], data: vec![0xaa, 0xbb], } @@ -143,9 +149,9 @@ fn policy() -> WalletPolicyConfig { "solana_1".into(), WalletAccountPolicy { allowed_programs: vec![ - TOKEN_PROGRAM.into(), + TOKEN_2022_PROGRAM.into(), ASSOCIATED_TOKEN_PROGRAM.into(), - base58(&filled(11)), + REWARDS_PROGRAM.to_string(), ], mints: vec![WalletMintCap { mint: mint(), @@ -173,6 +179,11 @@ fn spent(amount: u64, at: u64, index: u32, status: LedgerStatus) -> LedgerRecord account_index: index, address: SIGNER.into(), summary: summary_of(&[transfer_checked(&mint(), amount)]), + declared_debits: vec![MintTotal { + mint: mint(), + amount_raw: amount.to_string(), + }], + simulation: simulate::SimulationReport::default(), created_at_ms: at, expires_at_ms: at + QUOTE_TTL_MS, }; @@ -200,8 +211,8 @@ fn a_distributor_funding_transaction_decodes_into_its_summary() { summary.programs, vec![ ASSOCIATED_TOKEN_PROGRAM.to_string(), - TOKEN_PROGRAM.to_string(), - base58(&filled(11)) + TOKEN_2022_PROGRAM.to_string(), + REWARDS_PROGRAM.to_string() ] ); assert_eq!(summary.movements.len(), 1); @@ -218,7 +229,7 @@ fn a_distributor_funding_transaction_decodes_into_its_summary() { ); assert_eq!(summary.instructions[2].data_hex, "aabb"); assert_eq!( - evaluate_program(&policy(), "solana", 1, &summary, &[], NOW), + evaluate_program(&policy(), "solana", 1, &summary, &summary.totals, &[], NOW), Ok(()) ); } @@ -229,7 +240,7 @@ fn a_v0_message_without_lookup_tables_decodes() { let decoded = decode_transaction(&tx).unwrap(); assert!(decoded.versioned); let summary = summarize(&decoded, SIGNER).unwrap(); - assert_eq!(summary.programs, vec![base58(&filled(11))]); + assert_eq!(summary.programs, vec![REWARDS_PROGRAM.to_string()]); assert!(summary.totals.is_empty()); } @@ -248,27 +259,13 @@ fn malformed_bytes_are_rejected() { fn an_account_without_a_policy_section_is_refused() { let summary = summary_of(&[distributor_call()]); assert_eq!( - refusal_kind(evaluate_program( - &WalletPolicyConfig::default(), - "solana", - 1, - &summary, - &[], - NOW - )), + refusal_kind(evaluate_program(&WalletPolicyConfig::default(), "solana", 1, &summary, &summary.totals, &[], NOW)), RefusalKind::AccountNotAllowed ); // A section for index 1 does not open index 0 or index 2. for index in [0, 2] { assert_eq!( - refusal_kind(evaluate_program( - &policy(), - "solana", - index, - &summary, - &[], - NOW - )), + refusal_kind(evaluate_program(&policy(), "solana", index, &summary, &summary.totals, &[], NOW)), RefusalKind::AccountNotAllowed ); } @@ -282,7 +279,7 @@ fn an_unlisted_program_is_refused() { data: vec![], }; let summary = summary_of(&[distributor_call(), unlisted]); - let refused = evaluate_program(&policy(), "solana", 1, &summary, &[], NOW).unwrap_err(); + let refused = evaluate_program(&policy(), "solana", 1, &summary, &summary.totals, &[], NOW).unwrap_err(); assert_eq!(refused.kind, RefusalKind::ProgramNotAllowed); assert!( refused.message.contains(&base58(&filled(42))), @@ -303,12 +300,12 @@ fn a_transfer_over_the_per_transaction_cap_is_refused() { ]); assert_eq!(summary.totals[0].amount_raw, "1200"); assert_eq!( - refusal_kind(evaluate_program(&policy(), "solana", 1, &summary, &[], NOW)), + refusal_kind(evaluate_program(&policy(), "solana", 1, &summary, &summary.totals, &[], NOW)), RefusalKind::PerTransaction ); let at_cap = summary_of(&[transfer_checked(&mint(), 1_000)]); assert_eq!( - evaluate_program(&policy(), "solana", 1, &at_cap, &[], NOW), + evaluate_program(&policy(), "solana", 1, &at_cap, &at_cap.totals, &[], NOW), Ok(()) ); } @@ -323,7 +320,7 @@ fn the_rolling_day_cap_counts_only_this_accounts_program_records() { spent(1_000, NOW - DAY_MS - 1, 1, LedgerStatus::Broadcast), spent(1_000, NOW - 500, 2, LedgerStatus::Broadcast), ]; - let refused = evaluate_program(&policy(), "solana", 1, &summary, &records, NOW).unwrap_err(); + let refused = evaluate_program(&policy(), "solana", 1, &summary, &summary.totals, &records, NOW).unwrap_err(); assert_eq!(refused.kind, RefusalKind::Daily); assert!( refused.message.contains("1000 already spent"), @@ -333,21 +330,14 @@ fn the_rolling_day_cap_counts_only_this_accounts_program_records() { let small = summary_of(&[transfer_checked(&mint(), 500)]); assert_eq!( - evaluate_program(&policy(), "solana", 1, &small, &records, NOW), + evaluate_program(&policy(), "solana", 1, &small, &small.totals, &records, NOW), Ok(()) ); // An in-doubt attempt counts as spent. let mut in_doubt = records.clone(); in_doubt.push(spent(1, NOW - 10, 1, LedgerStatus::InDoubt)); assert_eq!( - refusal_kind(evaluate_program( - &policy(), - "solana", - 1, - &small, - &in_doubt, - NOW - )), + refusal_kind(evaluate_program(&policy(), "solana", 1, &small, &small.totals, &in_doubt, NOW)), RefusalKind::Daily ); } @@ -356,7 +346,7 @@ fn the_rolling_day_cap_counts_only_this_accounts_program_records() { fn an_unlisted_mint_is_refused() { let summary = summary_of(&[transfer_checked(&other_mint(), 1)]); assert_eq!( - refusal_kind(evaluate_program(&policy(), "solana", 1, &summary, &[], NOW)), + refusal_kind(evaluate_program(&policy(), "solana", 1, &summary, &summary.totals, &[], NOW)), RefusalKind::MintNotAllowed ); } @@ -379,7 +369,7 @@ fn two_mints_in_one_transaction_are_refused() { transfer_checked(&other_mint(), 1), ]); assert_eq!( - refusal_kind(evaluate_program(&policy, "solana", 1, &summary, &[], NOW)), + refusal_kind(evaluate_program(&policy, "solana", 1, &summary, &summary.totals, &[], NOW)), RefusalKind::TransactionNotAllowed ); } From d22a5fce72a87a2a9d0d64263db565fafc5918ac Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Sun, 15 Nov 2026 22:11:27 +0000 Subject: [PATCH 26/32] test(web3): add simulation tests for wallet program Adds unit tests covering the wallet program simulation path so the behaviour is exercised directly rather than only through higher-level flows. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../src/web3/wallet/program/simulate_tests.rs | 162 ++++++++++++++++++ 1 file changed, 162 insertions(+) create mode 100644 crates/openhuman-core/src/web3/wallet/program/simulate_tests.rs diff --git a/crates/openhuman-core/src/web3/wallet/program/simulate_tests.rs b/crates/openhuman-core/src/web3/wallet/program/simulate_tests.rs new file mode 100644 index 00000000000..52eab8d45f7 --- /dev/null +++ b/crates/openhuman-core/src/web3/wallet/program/simulate_tests.rs @@ -0,0 +1,162 @@ +use super::*; +use wiremock::matchers::{body_partial_json, method}; +use wiremock::{Mock, MockServer, ResponseTemplate}; + +const TINY_MINT: &str = "2AF7CqwieUjUPALL7icuZtL3X7wENdjUjGBMmfV2pump"; +const SIGNER: &str = "Hh8QwFUA6MtVu1qAoq12ucvFHNwCcVTV7hpWjeY1Hztb"; + +fn key(text: &str) -> [u8; 32] { + <[u8; 32]>::try_from(bs58::decode(text).into_vec().unwrap().as_slice()).unwrap() +} + +/// A Token-2022 account (base layout plus an extension tail). +fn token_account(mint: &str, owner: &str, amount: u64) -> Vec { + let mut data = vec![0u8; 182]; + data[..32].copy_from_slice(&key(mint)); + data[32..64].copy_from_slice(&key(owner)); + data[64..72].copy_from_slice(&amount.to_le_bytes()); + data +} + +fn state(mint: &str, owner: &str, amount: u64) -> TokenAccountState { + parse_token_account(&token_account(mint, owner, amount)).unwrap() +} + +fn total(mint: &str, amount: u64) -> MintTotal { + MintTotal { + mint: mint.to_string(), + amount_raw: amount.to_string(), + } +} + +fn other_mint() -> String { + base58(&[8u8; 32]) +} + +#[test] +fn token_accounts_parse_from_either_token_program_layout() { + let parsed = state(TINY_MINT, SIGNER, 42); + assert_eq!(parsed.mint, key(TINY_MINT)); + assert_eq!(parsed.owner, key(SIGNER)); + assert_eq!(parsed.amount, 42); + assert!(parse_token_account(&[0u8; 100]).is_none()); +} + +#[test] +fn debits_sum_the_drop_of_each_mint_and_ignore_credits() { + let owner = key(SIGNER); + let pre = [ + state(TINY_MINT, SIGNER, 1_000), + state(TINY_MINT, SIGNER, 500), + state(&other_mint(), SIGNER, 10), + ]; + // 300 leaves the first account, the second is closed, the other mint gains. + let post = [ + Some(state(TINY_MINT, SIGNER, 700)), + None, + Some(state(&other_mint(), SIGNER, 99)), + ]; + assert_eq!(debits(&owner, &pre, &post), vec![total(TINY_MINT, 800)]); + // An account handed to another owner counts as emptied. + let post = [ + Some(state(TINY_MINT, "11111111111111111111111111111111", 1_000)), + Some(state(TINY_MINT, SIGNER, 500)), + Some(state(&other_mint(), SIGNER, 10)), + ]; + assert_eq!(debits(&owner, &pre, &post), vec![total(TINY_MINT, 1_000)]); +} + +#[test] +fn the_simulated_debit_must_equal_the_declaration() { + let report = SimulationReport { + debits: vec![total(TINY_MINT, 600)], + ..SimulationReport::default() + }; + assert_eq!(check_simulation(&[total(TINY_MINT, 600)], &report), Ok(())); + for declared in [ + vec![total(TINY_MINT, 500)], + vec![total(TINY_MINT, 700)], + vec![], + vec![total(TINY_MINT, 600), total(&other_mint(), 1)], + ] { + let refused = check_simulation(&declared, &report).unwrap_err(); + assert_eq!(refused.kind, RefusalKind::SimulationMismatch, "{declared:?}"); + } + // A declared zero debit that simulates as zero is fine. + let nothing = SimulationReport::default(); + assert_eq!(check_simulation(&[total(TINY_MINT, 0)], ¬hing), Ok(())); +} + +#[test] +fn a_failing_simulation_is_refused() { + let report = SimulationReport { + err: Some(json!({"InstructionError": [1, "Custom"]})), + ..SimulationReport::default() + }; + let refused = check_simulation(&[], &report).unwrap_err(); + assert_eq!(refused.kind, RefusalKind::SimulationMismatch); + assert!(refused.message.contains("fails in simulation")); +} + +fn encoded(data: &[u8]) -> Value { + json!([base64::engine::general_purpose::STANDARD.encode(data), "base64"]) +} + +#[tokio::test] +async fn simulate_reads_the_owners_token_accounts_and_measures_the_cpi_debit() { + let server = MockServer::start().await; + let vault_source = "Source1111111111111111111111111111111111111"; + Mock::given(method("POST")) + .and(body_partial_json(json!({ + "method": "getTokenAccountsByOwner", + "params": [SIGNER, {"programId": TOKEN_2022_PROGRAM}] + }))) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({ + "jsonrpc": "2.0", "id": 1, + "result": {"context": {"slot": 1}, "value": [ + {"pubkey": vault_source, "account": {"data": encoded(&token_account(TINY_MINT, SIGNER, 5_000_000))}} + ]} + }))) + .mount(&server) + .await; + Mock::given(method("POST")) + .and(body_partial_json(json!({ + "method": "getTokenAccountsByOwner", + "params": [SIGNER, {"programId": TOKEN_PROGRAM}] + }))) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({ + "jsonrpc": "2.0", "id": 1, + "result": {"context": {"slot": 1}, "value": []} + }))) + .mount(&server) + .await; + Mock::given(method("POST")) + .and(body_partial_json(json!({ + "method": "simulateTransaction", + "params": [base64::engine::general_purpose::STANDARD.encode([1u8, 2, 3]), { + "sigVerify": false, + "accounts": {"encoding": "base64", "addresses": [vault_source]} + }] + }))) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({ + "jsonrpc": "2.0", "id": 1, + "result": {"context": {"slot": 2}, "value": { + "err": null, + "logs": [], + "unitsConsumed": 42_000, + "accounts": [{"data": encoded(&token_account(TINY_MINT, SIGNER, 4_000_000))}] + }} + }))) + .mount(&server) + .await; + + let report = simulate(&server.uri(), &[1, 2, 3], &key(SIGNER)) + .await + .expect("simulation"); + assert_eq!(report.err, None); + assert_eq!(report.debits, vec![total(TINY_MINT, 1_000_000)]); + assert_eq!(report.token_accounts, vec![vault_source.to_string()]); + assert_eq!(report.units_consumed, Some(42_000)); + assert_eq!(check_simulation(&[total(TINY_MINT, 1_000_000)], &report), Ok(())); + assert!(check_simulation(&[total(TINY_MINT, 999_999)], &report).is_err()); +} From 1b0491c6b07f6424ae2dd2cbf8daef19fcb1c237 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Sun, 15 Nov 2026 22:14:06 +0000 Subject: [PATCH 27/32] feat(wallet): require declared token debits confirmed by simulation Program transactions now take an `expectedDebits` field naming what the transaction withdraws from the account's token balances, and prepare only accepts a quote when simulation lowers those balances by exactly that amount. This pins programs that move tokens via CPI to the amount the mint caps were applied to, closing the gap where a distributor could debit more than declared. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../src/config/schema/wallet_policy.rs | 7 +- .../openhuman-core/src/web3/wallet/README.md | 13 +- .../src/web3/wallet/program/mod.rs | 41 ++-- .../src/web3/wallet/program/mod_tests.rs | 180 +++++++++++++++++- .../src/web3/wallet/program/ops.rs | 3 +- .../src/web3/wallet/program/simulate_tests.rs | 16 +- .../src/web3/wallet/schemas_tests.rs | 5 +- docs/gitbooks/en/features/wallet.md | 4 +- 8 files changed, 230 insertions(+), 39 deletions(-) diff --git a/crates/openhuman-core/src/config/schema/wallet_policy.rs b/crates/openhuman-core/src/config/schema/wallet_policy.rs index 7371c424a4e..f303b68ce1c 100644 --- a/crates/openhuman-core/src/config/schema/wallet_policy.rs +++ b/crates/openhuman-core/src/config/schema/wallet_policy.rs @@ -44,7 +44,7 @@ //! ```toml //! [wallet_policy.accounts.solana_1] //! allowed_programs = [ -//! "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA", # SPL Token +//! "TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb", # Token-2022 //! "ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL", # Associated Token Account //! "", # the program being called //! ] @@ -107,8 +107,9 @@ impl WalletPolicyConfig { /// What one account may sign through `wallet.execute_prepared_program`. /// -/// Every instruction of the transaction must invoke a listed program, and -/// every SPL token movement must be of a listed mint within its caps. +/// Every instruction of the transaction must invoke a listed program, and the +/// token debits the caller declares (and simulation confirms) must be of a +/// listed mint within its caps. #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] #[serde(default, deny_unknown_fields)] pub struct WalletAccountPolicy { diff --git a/crates/openhuman-core/src/web3/wallet/README.md b/crates/openhuman-core/src/web3/wallet/README.md index 895c7b6f1f9..f36e6966102 100644 --- a/crates/openhuman-core/src/web3/wallet/README.md +++ b/crates/openhuman-core/src/web3/wallet/README.md @@ -113,10 +113,15 @@ derives and stores its address on first use. under its own `[wallet_policy.accounts._]` section (`allowed_programs`, `mints` with `per_tx_max_raw` and `daily_max_raw`). The host decodes the transaction and refuses it unless the account is the fee -payer and sole signer, every program is listed, token instructions are -`TransferChecked` of one listed mint within its caps, ATA instructions are -creates, and there is no System instruction or lookup table. The quote holds -the exact bytes for 60 seconds; execute re-checks and reserves in the ledger +payer and sole signer, every program is listed, token instructions (SPL +Token or Token-2022) are `TransferChecked`, ATA instructions are creates, and +there is no System instruction or lookup table. The caller declares what the +transaction debits from the account's token balances (`expectedDebits`); the +caps apply to that, it must cover every visible transfer, and +`simulateTransaction` must lower the account's token balances by exactly that +much (`program/simulate.rs`), which is what pins a program that moves tokens +by CPI. The quote holds the exact bytes for 60 seconds; execute simulates +again, re-checks and reserves in the ledger (`kind = program`, `accountIndex`), signs the message bytes with a confidential `SignMessage`, and sends the transaction to the Solana RPC (the host override, else the module's default for the cluster). Program records diff --git a/crates/openhuman-core/src/web3/wallet/program/mod.rs b/crates/openhuman-core/src/web3/wallet/program/mod.rs index 89de509eaf6..de9f657ebd8 100644 --- a/crates/openhuman-core/src/web3/wallet/program/mod.rs +++ b/crates/openhuman-core/src/web3/wallet/program/mod.rs @@ -8,32 +8,41 @@ //! them sign anything: //! //! 1. **Prepare.** The caller hands over an unsigned Solana transaction -//! (base64 wire bytes, legacy or v0 without address lookup tables) and the -//! account index to sign with. The host decodes it and refuses it unless +//! (base64 wire bytes, legacy or v0 without address lookup tables), the +//! account index to sign with, and `expectedDebits`: what the transaction +//! takes from the account's token balances, per mint. The host decodes it +//! and refuses it unless //! - the account is the fee payer and the only signer; //! - every instruction invokes a program in the account's //! `allowed_programs` (`[wallet_policy.accounts.solana_]`); -//! - every SPL Token / Token-2022 instruction is a `TransferChecked` (the -//! only form that names its mint), and every Associated Token Account -//! instruction is a create; no top-level System program instruction; -//! - the mint moved is listed in the account's `mints`, at most one mint -//! per transaction, within its per-transaction cap and, with the spend -//! ledger, its rolling 24-hour cap. +//! - every SPL Token or Token-2022 instruction is a `TransferChecked` (the +//! only form that names its mint), every Associated Token Account +//! instruction is a create, and no instruction is the System program's; +//! - the declared debits cover every visible transfer and name at most one +//! mint, listed in the account's `mints`, within its per-transaction +//! cap and, with the spend ledger, its rolling 24-hour cap; +//! - `simulateTransaction` succeeds and lowers the account's token +//! balances by exactly the declared debits ([`simulate`]). This is what +//! holds a program that moves tokens by CPI (a distributor funding its +//! vault) to the amount the caps were applied to. //! //! It stores the exact bytes under a quote id for [`QUOTE_TTL_MS`] and //! returns the decoded summary (programs, instructions, token movements, -//! totals) for the caller to check against what it meant to build. +//! totals), the declared debits and the simulation, for the caller to +//! check against what it meant to build. //! 2. **Execute.** The caller names the quote and the account index again. -//! The host re-evaluates the policy against the ledger and reserves the -//! spend atomically (`ledger::SpendLedger::reserve`), asks the TinyWallet -//! module to sign the message bytes with the account's key (a confidential -//! `SignMessage`; the key never leaves the module), attaches the signature -//! and sends the transaction to the Solana RPC. The ledger record moves to -//! `broadcast` or `in_doubt`; a quote is never executed twice. +//! The host simulates again, re-evaluates the policy against the ledger +//! and reserves the spend atomically (`ledger::SpendLedger::reserve`), +//! asks the TinyWallet module to sign the message bytes with the account's +//! key (a confidential `SignMessage`; the key never leaves the module), +//! attaches the signature and sends the transaction to the Solana RPC. The +//! ledger record moves to `broadcast` or `in_doubt`; a quote is never +//! executed twice. //! //! Programs other than SPL Token, Token-2022 and Associated Token Account are //! opaque here: listing one is trusting it with the account's signature. The -//! caps bound only what top-level token instructions move. +//! caps bound the declared token debits, which simulation verifies; SOL spent +//! on fees and rent is not capped. //! //! The pure parts (decoding, summarising, the policy decision) are separate //! functions so they are tested without a module or a chain. diff --git a/crates/openhuman-core/src/web3/wallet/program/mod_tests.rs b/crates/openhuman-core/src/web3/wallet/program/mod_tests.rs index a63b0ac8d86..f86676f3f46 100644 --- a/crates/openhuman-core/src/web3/wallet/program/mod_tests.rs +++ b/crates/openhuman-core/src/web3/wallet/program/mod_tests.rs @@ -259,13 +259,29 @@ fn malformed_bytes_are_rejected() { fn an_account_without_a_policy_section_is_refused() { let summary = summary_of(&[distributor_call()]); assert_eq!( - refusal_kind(evaluate_program(&WalletPolicyConfig::default(), "solana", 1, &summary, &summary.totals, &[], NOW)), + refusal_kind(evaluate_program( + &WalletPolicyConfig::default(), + "solana", + 1, + &summary, + &summary.totals, + &[], + NOW + )), RefusalKind::AccountNotAllowed ); // A section for index 1 does not open index 0 or index 2. for index in [0, 2] { assert_eq!( - refusal_kind(evaluate_program(&policy(), "solana", index, &summary, &summary.totals, &[], NOW)), + refusal_kind(evaluate_program( + &policy(), + "solana", + index, + &summary, + &summary.totals, + &[], + NOW + )), RefusalKind::AccountNotAllowed ); } @@ -279,7 +295,8 @@ fn an_unlisted_program_is_refused() { data: vec![], }; let summary = summary_of(&[distributor_call(), unlisted]); - let refused = evaluate_program(&policy(), "solana", 1, &summary, &summary.totals, &[], NOW).unwrap_err(); + let refused = + evaluate_program(&policy(), "solana", 1, &summary, &summary.totals, &[], NOW).unwrap_err(); assert_eq!(refused.kind, RefusalKind::ProgramNotAllowed); assert!( refused.message.contains(&base58(&filled(42))), @@ -300,7 +317,15 @@ fn a_transfer_over_the_per_transaction_cap_is_refused() { ]); assert_eq!(summary.totals[0].amount_raw, "1200"); assert_eq!( - refusal_kind(evaluate_program(&policy(), "solana", 1, &summary, &summary.totals, &[], NOW)), + refusal_kind(evaluate_program( + &policy(), + "solana", + 1, + &summary, + &summary.totals, + &[], + NOW + )), RefusalKind::PerTransaction ); let at_cap = summary_of(&[transfer_checked(&mint(), 1_000)]); @@ -320,7 +345,16 @@ fn the_rolling_day_cap_counts_only_this_accounts_program_records() { spent(1_000, NOW - DAY_MS - 1, 1, LedgerStatus::Broadcast), spent(1_000, NOW - 500, 2, LedgerStatus::Broadcast), ]; - let refused = evaluate_program(&policy(), "solana", 1, &summary, &summary.totals, &records, NOW).unwrap_err(); + let refused = evaluate_program( + &policy(), + "solana", + 1, + &summary, + &summary.totals, + &records, + NOW, + ) + .unwrap_err(); assert_eq!(refused.kind, RefusalKind::Daily); assert!( refused.message.contains("1000 already spent"), @@ -337,7 +371,15 @@ fn the_rolling_day_cap_counts_only_this_accounts_program_records() { let mut in_doubt = records.clone(); in_doubt.push(spent(1, NOW - 10, 1, LedgerStatus::InDoubt)); assert_eq!( - refusal_kind(evaluate_program(&policy(), "solana", 1, &small, &small.totals, &in_doubt, NOW)), + refusal_kind(evaluate_program( + &policy(), + "solana", + 1, + &small, + &small.totals, + &in_doubt, + NOW + )), RefusalKind::Daily ); } @@ -346,7 +388,15 @@ fn the_rolling_day_cap_counts_only_this_accounts_program_records() { fn an_unlisted_mint_is_refused() { let summary = summary_of(&[transfer_checked(&other_mint(), 1)]); assert_eq!( - refusal_kind(evaluate_program(&policy(), "solana", 1, &summary, &summary.totals, &[], NOW)), + refusal_kind(evaluate_program( + &policy(), + "solana", + 1, + &summary, + &summary.totals, + &[], + NOW + )), RefusalKind::MintNotAllowed ); } @@ -369,7 +419,15 @@ fn two_mints_in_one_transaction_are_refused() { transfer_checked(&other_mint(), 1), ]); assert_eq!( - refusal_kind(evaluate_program(&policy, "solana", 1, &summary, &summary.totals, &[], NOW)), + refusal_kind(evaluate_program( + &policy, + "solana", + 1, + &summary, + &summary.totals, + &[], + NOW + )), RefusalKind::TransactionNotAllowed ); } @@ -492,6 +550,7 @@ async fn prepare_refuses_an_account_without_a_section_before_touching_the_wallet PrepareProgramParams { account_index: 1, transaction: base64::engine::general_purpose::STANDARD.encode(tx), + expected_debits: Vec::new(), }, ) .await @@ -517,3 +576,108 @@ async fn execute_refuses_an_unknown_quote() { assert!(error.contains("unavailable"), "{error}"); assert!(!has_quote_for_test("prog-missing")); } + +fn declared(mint: &str, amount: u64) -> Vec { + vec![MintTotal { + mint: mint.to_string(), + amount_raw: amount.to_string(), + }] +} + +#[test] +fn a_rewards_program_call_is_capped_by_its_declared_debit() { + // CreateMerkleDistribution funds the vault by CPI: no visible transfer, + // so the declaration carries the amount and the caps apply to it. + let summary = summary_of(&[ata_create(), distributor_call()]); + assert!(summary.totals.is_empty()); + let check = + |debits: &[MintTotal]| evaluate_program(&policy(), "solana", 1, &summary, debits, &[], NOW); + assert_eq!(check(&declared(&mint(), 1_000)), Ok(())); + assert_eq!(check(&[]), Ok(()), "a call that debits nothing (clawback)"); + assert_eq!( + refusal_kind(check(&declared(&mint(), 1_001))), + RefusalKind::PerTransaction + ); + assert_eq!( + refusal_kind(check(&declared(&other_mint(), 1))), + RefusalKind::MintNotAllowed + ); + let records = vec![spent(1_000, NOW - 1_000, 1, LedgerStatus::Broadcast)]; + assert_eq!( + refusal_kind(evaluate_program( + &policy(), + "solana", + 1, + &summary, + &declared(&mint(), 600), + &records, + NOW + )), + RefusalKind::Daily + ); +} + +#[test] +fn the_declaration_must_cover_every_visible_transfer() { + let summary = summary_of(&[transfer_checked(&mint(), 600), distributor_call()]); + let check = + |debits: &[MintTotal]| evaluate_program(&policy(), "solana", 1, &summary, debits, &[], NOW); + assert_eq!( + refusal_kind(check(&declared(&mint(), 599))), + RefusalKind::SimulationMismatch + ); + assert_eq!(refusal_kind(check(&[])), RefusalKind::SimulationMismatch); + // More than visible is allowed (the rest moves by CPI); simulation pins it. + assert_eq!(check(&declared(&mint(), 900)), Ok(())); + let twice = [declared(&mint(), 600), declared(&mint(), 600)].concat(); + assert_eq!( + refusal_kind(check(&twice)), + RefusalKind::TransactionNotAllowed + ); + let fractional = vec![MintTotal { + mint: mint(), + amount_raw: "1.5".into(), + }]; + assert_eq!( + refusal_kind(check(&fractional)), + RefusalKind::TransactionNotAllowed + ); +} + +#[test] +fn classic_token_transfer_checked_is_read_like_token_2022() { + let mut classic = transfer_checked(&mint(), 5); + classic.program = key(TOKEN_PROGRAM); + let summary = summary_of(&[classic]); + assert_eq!(summary.movements[0].program_id, TOKEN_PROGRAM); + assert_eq!(summary.totals, declared(&mint(), 5)); + // Not listed in this account's allowed_programs (only Token-2022 is). + assert_eq!( + refusal_kind(evaluate_program( + &policy(), + "solana", + 1, + &summary, + &summary.totals, + &[], + NOW + )), + RefusalKind::ProgramNotAllowed + ); +} + +#[test] +fn prepare_params_require_the_declared_debits() { + let missing = serde_json::from_value::(serde_json::json!({ + "accountIndex": 1, + "transaction": "AA==" + })); + assert!(missing.is_err()); + let parsed: PrepareProgramParams = serde_json::from_value(serde_json::json!({ + "accountIndex": 1, + "transaction": "AA==", + "expectedDebits": [{"mint": TINY_MINT, "amountRaw": "1000000"}] + })) + .unwrap(); + assert_eq!(parsed.expected_debits, declared(TINY_MINT, 1_000_000)); +} diff --git a/crates/openhuman-core/src/web3/wallet/program/ops.rs b/crates/openhuman-core/src/web3/wallet/program/ops.rs index e8dc1f3fe2f..459eb15b69a 100644 --- a/crates/openhuman-core/src/web3/wallet/program/ops.rs +++ b/crates/openhuman-core/src/web3/wallet/program/ops.rs @@ -20,8 +20,7 @@ use super::super::policy::{origin_refusal, refusal, ExecutionOrigin, PolicyRefus use super::simulate::{check_simulation, simulate, SimulationReport}; use super::{ attach_signature, base58, decode_transaction, evaluate_program, summarize, DecodedTransaction, - MintTotal, - ProgramTransactionSummary, LOG_PREFIX, QUOTE_PREFIX, QUOTE_TTL_MS, + MintTotal, ProgramTransactionSummary, LOG_PREFIX, QUOTE_PREFIX, QUOTE_TTL_MS, }; // ── Quotes ────────────────────────────────────────────────────────────────── diff --git a/crates/openhuman-core/src/web3/wallet/program/simulate_tests.rs b/crates/openhuman-core/src/web3/wallet/program/simulate_tests.rs index 52eab8d45f7..7730bf9027a 100644 --- a/crates/openhuman-core/src/web3/wallet/program/simulate_tests.rs +++ b/crates/openhuman-core/src/web3/wallet/program/simulate_tests.rs @@ -80,7 +80,11 @@ fn the_simulated_debit_must_equal_the_declaration() { vec![total(TINY_MINT, 600), total(&other_mint(), 1)], ] { let refused = check_simulation(&declared, &report).unwrap_err(); - assert_eq!(refused.kind, RefusalKind::SimulationMismatch, "{declared:?}"); + assert_eq!( + refused.kind, + RefusalKind::SimulationMismatch, + "{declared:?}" + ); } // A declared zero debit that simulates as zero is fine. let nothing = SimulationReport::default(); @@ -99,7 +103,10 @@ fn a_failing_simulation_is_refused() { } fn encoded(data: &[u8]) -> Value { - json!([base64::engine::general_purpose::STANDARD.encode(data), "base64"]) + json!([ + base64::engine::general_purpose::STANDARD.encode(data), + "base64" + ]) } #[tokio::test] @@ -157,6 +164,9 @@ async fn simulate_reads_the_owners_token_accounts_and_measures_the_cpi_debit() { assert_eq!(report.debits, vec![total(TINY_MINT, 1_000_000)]); assert_eq!(report.token_accounts, vec![vault_source.to_string()]); assert_eq!(report.units_consumed, Some(42_000)); - assert_eq!(check_simulation(&[total(TINY_MINT, 1_000_000)], &report), Ok(())); + assert_eq!( + check_simulation(&[total(TINY_MINT, 1_000_000)], &report), + Ok(()) + ); assert!(check_simulation(&[total(TINY_MINT, 999_999)], &report).is_err()); } diff --git a/crates/openhuman-core/src/web3/wallet/schemas_tests.rs b/crates/openhuman-core/src/web3/wallet/schemas_tests.rs index 1cec42309fa..49d5163a7b7 100644 --- a/crates/openhuman-core/src/web3/wallet/schemas_tests.rs +++ b/crates/openhuman-core/src/web3/wallet/schemas_tests.rs @@ -21,7 +21,10 @@ fn wallet_schema_wire_contracts_are_preserved() { ("tx_status", &["chain", "hash", "evmNetwork"][..]), ("execute_prepared", &["quoteId", "confirmed"][..]), ("account", &["chain", "accountIndex"][..]), - ("prepare_program", &["accountIndex", "transaction", "expectedDebits"][..]), + ( + "prepare_program", + &["accountIndex", "transaction", "expectedDebits"][..], + ), ("execute_prepared_program", &["accountIndex", "quoteId"][..]), ] { let schema = wallet_schemas(function); diff --git a/docs/gitbooks/en/features/wallet.md b/docs/gitbooks/en/features/wallet.md index 7d62e41f8e7..0429fe5fb6d 100644 --- a/docs/gitbooks/en/features/wallet.md +++ b/docs/gitbooks/en/features/wallet.md @@ -136,7 +136,7 @@ It can sign one thing: a Solana transaction another program built, through `wall ```toml [wallet_policy.accounts.solana_1] allowed_programs = [ - "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA", # SPL Token + "TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb", # Token-2022 (or the classic SPL Token program) "ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL", # Associated Token Account "", ] @@ -147,7 +147,7 @@ per_tx_max_raw = 1000000000 daily_max_raw = 2000000000 ``` -The transaction is refused if it calls a program not on the list, moves a mint not on the list, moves more than either cap, or needs any signer besides the account. Token movements must be `TransferChecked` instructions, and System program instructions are not signed this way. Executes are written to the same ledger, but they are counted separately from the primary account's caps. +The caller states what the transaction will take from the account's token balances. The transaction is refused if it calls a program not on the list, moves a mint not on the list, moves more than either cap, needs any signer besides the account, or, when simulated, takes a different amount than stated. Token movements must be `TransferChecked` instructions, and System program instructions are not signed this way. Executes are written to the same ledger, but they are counted separately from the primary account's caps. ## See also From 97d87f82016af7784f2fb205f484325c6c4be89b Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Sun, 15 Nov 2026 22:17:18 +0000 Subject: [PATCH 28/32] test(wallet): remove unused simulation report import Auto-committed-on: cuttlefish Co-authored-by: Medulla --- crates/openhuman-core/src/web3/wallet/program/mod_tests.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/crates/openhuman-core/src/web3/wallet/program/mod_tests.rs b/crates/openhuman-core/src/web3/wallet/program/mod_tests.rs index f86676f3f46..6ffcff1424a 100644 --- a/crates/openhuman-core/src/web3/wallet/program/mod_tests.rs +++ b/crates/openhuman-core/src/web3/wallet/program/mod_tests.rs @@ -5,7 +5,6 @@ use crate::web3::wallet::ledger::LedgerStatus; use crate::web3::wallet::ops::WalletChain; use crate::web3::wallet::policy::ExecutionOrigin; use base64::Engine as _; -use simulate::SimulationReport; /// `m/44'/501'/1'/0'` of the BIP-39 test phrase (see `ops_tests.rs`). const SIGNER: &str = "Hh8QwFUA6MtVu1qAoq12ucvFHNwCcVTV7hpWjeY1Hztb"; From 1ebf9b1aff9063d6e71cf61cb6bc8e716595611d Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Sun, 15 Nov 2026 22:19:58 +0000 Subject: [PATCH 29/32] feat(web3): verify co-signer signatures before signing solana transactions The transaction decoder now retains the signature slots, and signing places the account's signature in its own slot rather than always slot zero. Every other required signer must already have a valid ed25519 signature over the message, so partially signed host-built transactions can be co-signed safely. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- crates/openhuman-core/Cargo.toml | 4 + .../src/web3/wallet/program/mod.rs | 112 +++++++++++++++--- .../src/web3/wallet/program/ops.rs | 18 ++- 3 files changed, 115 insertions(+), 19 deletions(-) diff --git a/crates/openhuman-core/Cargo.toml b/crates/openhuman-core/Cargo.toml index cd49b0bad85..6a03db7e91b 100644 --- a/crates/openhuman-core/Cargo.toml +++ b/crates/openhuman-core/Cargo.toml @@ -456,6 +456,9 @@ tinywallet-bus = { path = "../../vendor/tinywallet/crates/tinywallet-bus", defau # which decodes a host-built transaction to check it against the account's # policy before the module signs it. A codec only; no key material. bs58 = { version = "0.5", optional = true } +# Verifies (never makes) the co-signers' ed25519 signatures on a partially +# signed host-built Solana transaction before the module adds the account's. +ed25519-dalek = { version = "2.2", optional = true } [target.'cfg(windows)'.dependencies] @@ -726,6 +729,7 @@ voice = [ web3 = [ "dep:tinywallet-bus", "dep:bs58", + "dep:ed25519-dalek", "modules", ] diff --git a/crates/openhuman-core/src/web3/wallet/program/mod.rs b/crates/openhuman-core/src/web3/wallet/program/mod.rs index de9f657ebd8..29d8fe66bae 100644 --- a/crates/openhuman-core/src/web3/wallet/program/mod.rs +++ b/crates/openhuman-core/src/web3/wallet/program/mod.rs @@ -12,7 +12,9 @@ //! account index to sign with, and `expectedDebits`: what the transaction //! takes from the account's token balances, per mint. The host decodes it //! and refuses it unless -//! - the account is the fee payer and the only signer; +//! - the account is the fee payer, and every other required signer (a +//! throwaway keypair the caller generated, say) has already signed the +//! message with a valid signature; //! - every instruction invokes a program in the account's //! `allowed_programs` (`[wallet_policy.accounts.solana_]`); //! - every SPL Token or Token-2022 instruction is a `TransferChecked` (the @@ -35,7 +37,8 @@ //! and reserves the spend atomically (`ledger::SpendLedger::reserve`), //! asks the TinyWallet module to sign the message bytes with the account's //! key (a confidential `SignMessage`; the key never leaves the module), -//! attaches the signature and sends the transaction to the Solana RPC. The +//! puts the signature in the account's signer slot, verifies every +//! signature, and sends the transaction to the Solana RPC. The //! ledger record moves to `broadcast` or `in_doubt`; a quote is never //! executed twice. //! @@ -97,6 +100,8 @@ pub struct DecodedTransaction { pub signature_count: usize, /// Byte offset of the first signature slot. pub signatures_offset: usize, + /// The signature slots as given (all zeros when unsigned). + pub signatures: Vec<[u8; 64]>, /// The serialized message, exactly as it is signed. pub message: Vec, /// Whether the message is versioned (v0). @@ -170,11 +175,19 @@ pub fn decode_transaction(bytes: &[u8]) -> Result { let mut reader = Reader { bytes, pos: 0 }; let signature_count = reader.compact_u16()?; let signatures_offset = reader.pos; - reader.take( - signature_count - .checked_mul(64) - .ok_or("too many signatures")?, - )?; + let signatures = reader + .take( + signature_count + .checked_mul(64) + .ok_or("too many signatures")?, + )? + .chunks_exact(64) + .map(|chunk| { + let mut signature = [0u8; 64]; + signature.copy_from_slice(chunk); + signature + }) + .collect(); let message_start = reader.pos; let first = *bytes @@ -228,6 +241,7 @@ pub fn decode_transaction(bytes: &[u8]) -> Result { Ok(DecodedTransaction { signature_count, signatures_offset, + signatures, message: bytes[message_start..].to_vec(), versioned, num_required_signatures, @@ -238,24 +252,75 @@ pub fn decode_transaction(bytes: &[u8]) -> Result { }) } -/// `bytes` with signature slot 0 replaced by `signature`. +/// `bytes` with `signature` in every signer slot whose key is `signer`. /// /// # Errors /// -/// When the transaction has no signature slot. +/// When `signer` holds no signer slot. pub fn attach_signature( bytes: &[u8], decoded: &DecodedTransaction, + signer: &[u8; 32], signature: &[u8; 64], ) -> Result, String> { - if decoded.signature_count == 0 { - return Err("transaction has no signature slot".to_string()); - } let mut signed = bytes.to_vec(); - signed[decoded.signatures_offset..decoded.signatures_offset + 64].copy_from_slice(signature); + let mut placed = false; + for slot in 0..decoded.signature_count { + if decoded.account_keys.get(slot) == Some(signer) { + let at = decoded.signatures_offset + slot * 64; + signed[at..at + 64].copy_from_slice(signature); + placed = true; + } + } + if !placed { + return Err("the signing account holds no signer slot in the transaction".to_string()); + } Ok(signed) } +/// Whether `signature` is a valid ed25519 signature by `key` over `message`. +#[must_use] +pub fn signature_is_valid(key: &[u8; 32], message: &[u8], signature: &[u8; 64]) -> bool { + ed25519_dalek::VerifyingKey::from_bytes(key).is_ok_and(|key| { + key.verify_strict(message, &ed25519_dalek::Signature::from_bytes(signature)) + .is_ok() + }) +} + +/// Refuse unless every required signer other than `signer` has already +/// signed the message validly (the caller co-signs before preparing; a +/// throwaway `seed` keypair, say). `signer`'s own slots may hold anything: +/// the module's signature replaces them. +/// +/// # Errors +/// +/// The refusal naming the first unsigned or wrongly signed signer. +pub fn check_cosigners(tx: &DecodedTransaction, signer: &[u8; 32]) -> Result<(), PolicyRefusal> { + for slot in 0..tx.signature_count { + let key = tx + .account_keys + .get(slot) + .ok_or_else(|| structural("a signer slot has no account key"))?; + if key == signer { + continue; + } + let signature = &tx.signatures[slot]; + if signature.iter().all(|byte| *byte == 0) { + return Err(structural(format!( + "required signer {} has not signed; co-sign before preparing", + base58(key) + ))); + } + if !signature_is_valid(key, &tx.message, signature) { + return Err(structural(format!( + "the signature of required signer {} does not verify over the message", + base58(key) + ))); + } + } + Ok(()) +} + pub(super) fn base58(bytes: &[u8]) -> String { bs58::encode(bytes).into_string() } @@ -300,8 +365,11 @@ pub struct MintTotal { #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ProgramTransactionSummary { - /// The fee payer and only signer: the signing account's address. + /// The fee payer: the signing account's address. pub fee_payer: String, + /// Every required signer, fee payer first. All but the signing account + /// have already signed (verified). + pub signers: Vec, pub recent_blockhash: String, /// Distinct program ids, in first-use order. pub programs: Vec, @@ -321,7 +389,8 @@ fn forbidden(message: impl Into) -> PolicyRefusal { } /// Decode `tx` into its summary and check what the host refuses whatever the -/// policy says: `signer` must be the fee payer and the only signer, no lookup +/// policy says: `signer` must be the fee payer, every other required signer +/// must already have signed validly ([`check_cosigners`]), no lookup /// tables, and only the token, ATA and System instructions this path can /// account for. /// @@ -338,10 +407,11 @@ pub fn summarize( list every account in the message", )); } - if tx.num_required_signatures != 1 || tx.signature_count != 1 { + if tx.num_required_signatures == 0 + || usize::from(tx.num_required_signatures) != tx.signature_count + { return Err(structural(format!( - "the transaction needs {} signatures over {} slots; only a transaction the \ - account signs alone is supported", + "the transaction needs {} signatures but carries {} slots", tx.num_required_signatures, tx.signature_count ))); } @@ -355,6 +425,11 @@ pub fn summarize( "the fee payer {fee_payer} is not the signing account {signer}" ))); } + check_cosigners(tx, &tx.account_keys[0])?; + let signers = tx.account_keys[..tx.signature_count] + .iter() + .map(|key| base58(key)) + .collect(); let key = |index: u8| -> Result { tx.account_keys @@ -420,6 +495,7 @@ pub fn summarize( .collect(); Ok(ProgramTransactionSummary { fee_payer, + signers, recent_blockhash: base58(&tx.recent_blockhash), programs, instructions, diff --git a/crates/openhuman-core/src/web3/wallet/program/ops.rs b/crates/openhuman-core/src/web3/wallet/program/ops.rs index 459eb15b69a..47dc6fea2a4 100644 --- a/crates/openhuman-core/src/web3/wallet/program/ops.rs +++ b/crates/openhuman-core/src/web3/wallet/program/ops.rs @@ -409,7 +409,23 @@ async fn sign_and_send( } _ => return Err("wallet module returned a non-ed25519 signature".to_string()), }; - let signed_transaction = attach_signature(&stored.transaction, &stored.decoded, &signature)?; + let signer = stored + .decoded + .account_keys + .first() + .ok_or_else(|| "the transaction lists no accounts".to_string())?; + let signed_transaction = + attach_signature(&stored.transaction, &stored.decoded, signer, &signature)?; + // Every slot must now hold a valid signature: the co-signers' were checked + // at prepare, and this proves the module signed with the fee payer's key. + let signed = decode_transaction(&signed_transaction)?; + for (slot, signature) in signed.signatures.iter().enumerate() { + if !super::signature_is_valid(&signed.account_keys[slot], &signed.message, signature) { + return Err(format!( + "signature {slot} does not verify; the transaction was not sent" + )); + } + } let url = solana_rpc_url(ctx).await?; let encoded = base64::engine::general_purpose::STANDARD.encode(signed_transaction); let hash: String = super::super::rpc::rpc_call_to( From ef6444689341c4c3d006d90ce10b3c2d1e5b76c9 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Sun, 15 Nov 2026 22:20:10 +0000 Subject: [PATCH 30/32] docs(wallet): document co-signer support in program transactions Update the wallet docs and schema descriptions to state that a program transaction may carry other required signers as long as they have already signed validly, with only the account's own signer slot left empty. The previous wording claimed the account had to be the sole signer, which no longer matches the policy check. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- crates/openhuman-core/src/web3/wallet/README.md | 2 +- crates/openhuman-core/src/web3/wallet/program/ops.rs | 5 +++-- crates/openhuman-core/src/web3/wallet/program/schemas.rs | 6 +++--- docs/gitbooks/en/features/wallet.md | 2 +- 4 files changed, 8 insertions(+), 7 deletions(-) diff --git a/crates/openhuman-core/src/web3/wallet/README.md b/crates/openhuman-core/src/web3/wallet/README.md index f36e6966102..a0aacdf2284 100644 --- a/crates/openhuman-core/src/web3/wallet/README.md +++ b/crates/openhuman-core/src/web3/wallet/README.md @@ -113,7 +113,7 @@ derives and stores its address on first use. under its own `[wallet_policy.accounts._]` section (`allowed_programs`, `mints` with `per_tx_max_raw` and `daily_max_raw`). The host decodes the transaction and refuses it unless the account is the fee -payer and sole signer, every program is listed, token instructions (SPL +payer, every other required signer has already signed validly, every program is listed, token instructions (SPL Token or Token-2022) are `TransferChecked`, ATA instructions are creates, and there is no System instruction or lookup table. The caller declares what the transaction debits from the account's token balances (`expectedDebits`); the diff --git a/crates/openhuman-core/src/web3/wallet/program/ops.rs b/crates/openhuman-core/src/web3/wallet/program/ops.rs index 47dc6fea2a4..a365603dbef 100644 --- a/crates/openhuman-core/src/web3/wallet/program/ops.rs +++ b/crates/openhuman-core/src/web3/wallet/program/ops.rs @@ -61,8 +61,9 @@ pub struct ExecutedProgram { pub struct PrepareProgramParams { #[serde(alias = "account_index")] pub account_index: u32, - /// Base64 of the unsigned transaction's wire bytes (signature slots - /// zeroed), e.g. `transaction.serialize({requireAllSignatures: false})`. + /// Base64 of the transaction's wire bytes, e.g. + /// `transaction.serialize({requireAllSignatures: false})`: the account's + /// signer slot empty, every other required signer's slot already signed. pub transaction: String, /// What the transaction debits from the account's token balances, per /// mint (`[{mint, amountRaw}]`, empty when it debits nothing). The caps diff --git a/crates/openhuman-core/src/web3/wallet/program/schemas.rs b/crates/openhuman-core/src/web3/wallet/program/schemas.rs index 27a6a14550e..7a4e4bc4ece 100644 --- a/crates/openhuman-core/src/web3/wallet/program/schemas.rs +++ b/crates/openhuman-core/src/web3/wallet/program/schemas.rs @@ -58,10 +58,10 @@ pub(crate) fn schema(function: &str) -> ControllerSchema { "prepare_program" => ControllerSchema { namespace: "wallet", function: "prepare_program", - description: "Check a host-built unsigned Solana transaction against [wallet_policy.accounts.solana_] and hold it as a quote for 60 seconds. Refused (WALLET_POLICY_REFUSED:) unless the account has a section, is the fee payer and only signer, every instruction invokes an allowed program, token instructions (SPL Token or Token-2022) are TransferChecked, the declared expectedDebits cover them and name at most one listed mint within its per-transaction and rolling 24h caps, ATA instructions are creates, there is no System program instruction or address lookup table, and simulateTransaction succeeds and debits the account's token accounts by exactly expectedDebits.", + description: "Check a host-built unsigned Solana transaction against [wallet_policy.accounts.solana_] and hold it as a quote for 60 seconds. Refused (WALLET_POLICY_REFUSED:) unless the account has a section, is the fee payer, every other required signer has already signed the message validly (the account's own slot may be empty), every instruction invokes an allowed program, token instructions (SPL Token or Token-2022) are TransferChecked, the declared expectedDebits cover them and name at most one listed mint within its per-transaction and rolling 24h caps, ATA instructions are creates, there is no System program instruction or address lookup table, and simulateTransaction succeeds and debits the account's token accounts by exactly expectedDebits.", inputs: vec![ required_json("accountIndex", "Index of the Solana account that signs (1 is m/44'/501'/1'/0')."), - required_json("transaction", "Base64 of the unsigned transaction's wire bytes (legacy or v0, signature slots zeroed)."), + required_json("transaction", "Base64 of the transaction's wire bytes (legacy or v0): the account's signer slot empty, every other required signer's slot already signed."), required_json("expectedDebits", "Array of {mint, amountRaw}: what the transaction debits from the account's token balances (SPL Token or Token-2022), per mint; [] when nothing. Caps apply to these amounts and the simulation must debit exactly them."), ], outputs: vec![FieldSchema { @@ -74,7 +74,7 @@ pub(crate) fn schema(function: &str) -> ControllerSchema { "execute_prepared_program" => ControllerSchema { namespace: "wallet", function: "execute_prepared_program", - description: "Sign a prepared program transaction with the account's key inside the wallet module and send it to the Solana RPC. The transaction is simulated again and the policy re-checked, and the spend reserved in the ledger first; the attempt is recorded broadcast or in_doubt and a quote is never executed twice.", + description: "Sign a prepared program transaction (in the account's signer slot) with the account's key inside the wallet module and send it to the Solana RPC. The transaction is simulated again and the policy re-checked, and the spend reserved in the ledger first; the attempt is recorded broadcast or in_doubt and a quote is never executed twice.", inputs: vec![ required_json("accountIndex", "The account index the quote was prepared for."), required_json("quoteId", "quoteId returned by wallet.prepare_program."), diff --git a/docs/gitbooks/en/features/wallet.md b/docs/gitbooks/en/features/wallet.md index 0429fe5fb6d..9e0aa904928 100644 --- a/docs/gitbooks/en/features/wallet.md +++ b/docs/gitbooks/en/features/wallet.md @@ -147,7 +147,7 @@ per_tx_max_raw = 1000000000 daily_max_raw = 2000000000 ``` -The caller states what the transaction will take from the account's token balances. The transaction is refused if it calls a program not on the list, moves a mint not on the list, moves more than either cap, needs any signer besides the account, or, when simulated, takes a different amount than stated. Token movements must be `TransferChecked` instructions, and System program instructions are not signed this way. Executes are written to the same ledger, but they are counted separately from the primary account's caps. +The caller states what the transaction will take from the account's token balances. The transaction is refused if it calls a program not on the list, moves a mint not on the list, moves more than either cap, needs another signer that has not already signed it, or, when simulated, takes a different amount than stated. Token movements must be `TransferChecked` instructions, and System program instructions are not signed this way. Executes are written to the same ledger, but they are counted separately from the primary account's caps. ## See also From 5243836713791c8f79ea3ba8bd579d710437bc2a Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Sun, 15 Nov 2026 22:23:38 +0000 Subject: [PATCH 31/32] test(web3): cover co-signed rewards distributions and signature attachment Split the combined refusal test into separate cases and add coverage for a Rewards distribution co-signed by the seed key, which is now accepted once the seed has signed and still subject to the per-transaction cap. Also verify that a co-signature which does not verify is refused and that attaching the account's signature fills its own slot while leaving the seed's signature and the message intact. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- Cargo.lock | 1 + .../src/web3/wallet/program/mod_tests.rs | 128 +++++++++++++++++- 2 files changed, 124 insertions(+), 5 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index a898b4d9085..c56a15d7bb9 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5691,6 +5691,7 @@ dependencies = [ "directories", "dirs 6.0.0", "dotenvy", + "ed25519-dalek", "env_logger", "flate2", "fs2", diff --git a/crates/openhuman-core/src/web3/wallet/program/mod_tests.rs b/crates/openhuman-core/src/web3/wallet/program/mod_tests.rs index 6ffcff1424a..3a7b99b3594 100644 --- a/crates/openhuman-core/src/web3/wallet/program/mod_tests.rs +++ b/crates/openhuman-core/src/web3/wallet/program/mod_tests.rs @@ -438,17 +438,135 @@ fn summarize_kind(tx: &[u8], signer: &str) -> RefusalKind { } #[test] -fn a_transaction_another_key_pays_for_or_cosigns_is_refused() { +fn a_transaction_another_key_pays_for_is_refused() { let tx = build(filled(4), 1, &[distributor_call()], None); assert_eq!( summarize_kind(&tx, SIGNER), RefusalKind::TransactionNotAllowed ); - let cosigned = build(key(SIGNER), 2, &[distributor_call()], None); +} + +/// The throwaway `seed` keypair the host generates per Rewards round. +fn seed_key() -> ed25519_dalek::SigningKey { + ed25519_dalek::SigningKey::from_bytes(&[21u8; 32]) +} + +/// Rewards `CreateMerkleDistribution` (ix 5): signers are the payer and +/// authority (both the index-1 account) and the seed; it funds the vault from +/// the account's TINY token account by a Token-2022 CPI. +fn create_distribution() -> Ix { + Ix { + program: key(REWARDS_PROGRAM), + accounts: vec![ + seed_key().verifying_key().to_bytes(), + key(SIGNER), + filled(3), + filled(1), + key(&mint()), + key(TOKEN_2022_PROGRAM), + key(SYSTEM_PROGRAM), + ], + data: vec![5, 0xaa], + } +} + +/// `tx` with signature slot `slot` set to `signature`. +fn with_signature(tx: &[u8], slot: usize, signature: &[u8; 64]) -> Vec { + let decoded = decode_transaction(tx).unwrap(); + let mut out = tx.to_vec(); + let at = decoded.signatures_offset + slot * 64; + out[at..at + 64].copy_from_slice(signature); + out +} + +fn seed_signed(tx: &[u8]) -> Vec { + use ed25519_dalek::Signer as _; + let message = decode_transaction(tx).unwrap().message; + with_signature(tx, 1, &seed_key().sign(&message).to_bytes()) +} + +#[test] +fn a_co_signed_rewards_distribution_is_accepted_once_the_seed_has_signed() { + let unsigned = build(key(SIGNER), 2, &[create_distribution()], None); + let decoded = decode_transaction(&unsigned).unwrap(); assert_eq!( - summarize_kind(&cosigned, SIGNER), - RefusalKind::TransactionNotAllowed + base58(&decoded.account_keys[1]), + base58(&seed_key().verifying_key().to_bytes()) + ); + // The seed has not signed yet. + let refused = summarize(&decoded, SIGNER).unwrap_err(); + assert_eq!(refused.kind, RefusalKind::TransactionNotAllowed); + assert!( + refused.message.contains("has not signed"), + "{}", + refused.message + ); + + let signed = seed_signed(&unsigned); + let summary = summarize(&decode_transaction(&signed).unwrap(), SIGNER).unwrap(); + assert_eq!(summary.signers.len(), 2); + assert_eq!(summary.signers[0], SIGNER); + assert_eq!(summary.programs, vec![REWARDS_PROGRAM.to_string()]); + // The vault is funded by CPI: nothing visible, so the declared debit is + // what the caps (1000 per transaction) apply to. + assert!(summary.totals.is_empty()); + let check = + |debits: &[MintTotal]| evaluate_program(&policy(), "solana", 1, &summary, debits, &[], NOW); + assert_eq!(check(&declared(&mint(), 1_000)), Ok(())); + assert_eq!( + refusal_kind(check(&declared(&mint(), 5_000))), + RefusalKind::PerTransaction + ); +} + +#[test] +fn a_co_signature_that_does_not_verify_is_refused() { + let unsigned = build(key(SIGNER), 2, &[create_distribution()], None); + // Signed over other bytes, and garbage. + let other = { + use ed25519_dalek::Signer as _; + seed_key().sign(b"something else").to_bytes() + }; + for signature in [other, [0x11; 64]] { + let tx = with_signature(&unsigned, 1, &signature); + let refused = summarize(&decode_transaction(&tx).unwrap(), SIGNER).unwrap_err(); + assert_eq!(refused.kind, RefusalKind::TransactionNotAllowed); + assert!( + refused.message.contains("does not verify"), + "{}", + refused.message + ); + } +} + +#[test] +fn the_accounts_signature_fills_its_own_slot_and_completes_the_transaction() { + use ed25519_dalek::Signer as _; + let tx = seed_signed(&build(key(SIGNER), 2, &[create_distribution()], None)); + let decoded = decode_transaction(&tx).unwrap(); + // Stand-in for the module: any key's signature lands in the account's slot. + let ours = ed25519_dalek::SigningKey::from_bytes(&[33u8; 32]); + let signature = ours.sign(&decoded.message).to_bytes(); + let signed = attach_signature(&tx, &decoded, &key(SIGNER), &signature).unwrap(); + let after = decode_transaction(&signed).unwrap(); + assert_eq!(after.signatures[0], signature); + assert_eq!( + after.signatures[1], decoded.signatures[1], + "the seed's stays" ); + assert_eq!(after.message, decoded.message); + assert!(signature_is_valid( + &key(&base58(&seed_key().verifying_key().to_bytes())), + &after.message, + &after.signatures[1] + )); + assert!(signature_is_valid( + &ours.verifying_key().to_bytes(), + &after.message, + &after.signatures[0] + )); + // A key holding no signer slot cannot be placed. + assert!(attach_signature(&tx, &decoded, &filled(3), &signature).is_err()); } #[test] @@ -506,7 +624,7 @@ fn system_and_unaccountable_token_instructions_are_refused_whatever_the_policy() fn the_signature_lands_in_slot_zero_and_the_message_is_untouched() { let tx = build(key(SIGNER), 1, &[distributor_call()], None); let decoded = decode_transaction(&tx).unwrap(); - let signed = attach_signature(&tx, &decoded, &[0xab; 64]).unwrap(); + let signed = attach_signature(&tx, &decoded, &key(SIGNER), &[0xab; 64]).unwrap(); assert_eq!(&signed[1..65], &[0xab; 64][..]); assert_eq!(&signed[65..], decoded.message.as_slice()); assert_eq!( From dacda387598b1d182aa0dcd082ff025d2f94d573 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Sun, 15 Nov 2026 22:26:59 +0000 Subject: [PATCH 32/32] refactor(web3): use as_chunks for signature parsing and share test helpers Replaced the manual chunk-and-copy loop in transaction decoding with slice as_chunks, and moved the co-signing tests into their own module while exposing the shared fixtures from mod_tests so both test files can use them. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../src/web3/wallet/program/cosign_tests.rs | 127 +++++++++++++++ .../src/web3/wallet/program/mod.rs | 13 +- .../src/web3/wallet/program/mod_tests.rs | 151 ++---------------- 3 files changed, 147 insertions(+), 144 deletions(-) create mode 100644 crates/openhuman-core/src/web3/wallet/program/cosign_tests.rs diff --git a/crates/openhuman-core/src/web3/wallet/program/cosign_tests.rs b/crates/openhuman-core/src/web3/wallet/program/cosign_tests.rs new file mode 100644 index 00000000000..ca785366446 --- /dev/null +++ b/crates/openhuman-core/src/web3/wallet/program/cosign_tests.rs @@ -0,0 +1,127 @@ +use super::tests::{ + build, declared, filled, key, mint, policy, refusal_kind, Ix, NOW, REWARDS_PROGRAM, SIGNER, +}; +use super::*; + +/// The throwaway `seed` keypair the host generates per Rewards round. +fn seed_key() -> ed25519_dalek::SigningKey { + ed25519_dalek::SigningKey::from_bytes(&[21u8; 32]) +} + +/// Rewards `CreateMerkleDistribution` (ix 5): signers are the payer and +/// authority (both the index-1 account) and the seed; it funds the vault from +/// the account's TINY token account by a Token-2022 CPI. +fn create_distribution() -> Ix { + Ix { + program: key(REWARDS_PROGRAM), + accounts: vec![ + seed_key().verifying_key().to_bytes(), + key(SIGNER), + filled(3), + filled(1), + key(&mint()), + key(TOKEN_2022_PROGRAM), + key(SYSTEM_PROGRAM), + ], + data: vec![5, 0xaa], + } +} + +/// `tx` with signature slot `slot` set to `signature`. +fn with_signature(tx: &[u8], slot: usize, signature: &[u8; 64]) -> Vec { + let decoded = decode_transaction(tx).unwrap(); + let mut out = tx.to_vec(); + let at = decoded.signatures_offset + slot * 64; + out[at..at + 64].copy_from_slice(signature); + out +} + +fn seed_signed(tx: &[u8]) -> Vec { + use ed25519_dalek::Signer as _; + let message = decode_transaction(tx).unwrap().message; + with_signature(tx, 1, &seed_key().sign(&message).to_bytes()) +} + +#[test] +fn a_co_signed_rewards_distribution_is_accepted_once_the_seed_has_signed() { + let unsigned = build(key(SIGNER), 2, &[create_distribution()], None); + let decoded = decode_transaction(&unsigned).unwrap(); + assert_eq!( + base58(&decoded.account_keys[1]), + base58(&seed_key().verifying_key().to_bytes()) + ); + // The seed has not signed yet. + let refused = summarize(&decoded, SIGNER).unwrap_err(); + assert_eq!(refused.kind, RefusalKind::TransactionNotAllowed); + assert!( + refused.message.contains("has not signed"), + "{}", + refused.message + ); + + let signed = seed_signed(&unsigned); + let summary = summarize(&decode_transaction(&signed).unwrap(), SIGNER).unwrap(); + assert_eq!(summary.signers.len(), 2); + assert_eq!(summary.signers[0], SIGNER); + assert_eq!(summary.programs, vec![REWARDS_PROGRAM.to_string()]); + // The vault is funded by CPI: nothing visible, so the declared debit is + // what the caps (1000 per transaction) apply to. + assert!(summary.totals.is_empty()); + let check = + |debits: &[MintTotal]| evaluate_program(&policy(), "solana", 1, &summary, debits, &[], NOW); + assert_eq!(check(&declared(&mint(), 1_000)), Ok(())); + assert_eq!( + refusal_kind(check(&declared(&mint(), 5_000))), + RefusalKind::PerTransaction + ); +} + +#[test] +fn a_co_signature_that_does_not_verify_is_refused() { + let unsigned = build(key(SIGNER), 2, &[create_distribution()], None); + // Signed over other bytes, and garbage. + let other = { + use ed25519_dalek::Signer as _; + seed_key().sign(b"something else").to_bytes() + }; + for signature in [other, [0x11; 64]] { + let tx = with_signature(&unsigned, 1, &signature); + let refused = summarize(&decode_transaction(&tx).unwrap(), SIGNER).unwrap_err(); + assert_eq!(refused.kind, RefusalKind::TransactionNotAllowed); + assert!( + refused.message.contains("does not verify"), + "{}", + refused.message + ); + } +} + +#[test] +fn the_accounts_signature_fills_its_own_slot_and_completes_the_transaction() { + use ed25519_dalek::Signer as _; + let tx = seed_signed(&build(key(SIGNER), 2, &[create_distribution()], None)); + let decoded = decode_transaction(&tx).unwrap(); + // Stand-in for the module: any key's signature lands in the account's slot. + let ours = ed25519_dalek::SigningKey::from_bytes(&[33u8; 32]); + let signature = ours.sign(&decoded.message).to_bytes(); + let signed = attach_signature(&tx, &decoded, &key(SIGNER), &signature).unwrap(); + let after = decode_transaction(&signed).unwrap(); + assert_eq!(after.signatures[0], signature); + assert_eq!( + after.signatures[1], decoded.signatures[1], + "the seed's stays" + ); + assert_eq!(after.message, decoded.message); + assert!(signature_is_valid( + &key(&base58(&seed_key().verifying_key().to_bytes())), + &after.message, + &after.signatures[1] + )); + assert!(signature_is_valid( + &ours.verifying_key().to_bytes(), + &after.message, + &after.signatures[0] + )); + // A key holding no signer slot cannot be placed. + assert!(attach_signature(&tx, &decoded, &filled(3), &signature).is_err()); +} diff --git a/crates/openhuman-core/src/web3/wallet/program/mod.rs b/crates/openhuman-core/src/web3/wallet/program/mod.rs index 29d8fe66bae..307a5d6c59a 100644 --- a/crates/openhuman-core/src/web3/wallet/program/mod.rs +++ b/crates/openhuman-core/src/web3/wallet/program/mod.rs @@ -181,13 +181,9 @@ pub fn decode_transaction(bytes: &[u8]) -> Result { .checked_mul(64) .ok_or("too many signatures")?, )? - .chunks_exact(64) - .map(|chunk| { - let mut signature = [0u8; 64]; - signature.copy_from_slice(chunk); - signature - }) - .collect(); + .as_chunks::<64>() + .0 + .to_vec(); let message_start = reader.pos; let first = *bytes @@ -696,6 +692,9 @@ pub use ops::{ #[cfg(test)] pub(crate) use ops::{has_quote_for_test, program_record}; +#[cfg(test)] +#[path = "cosign_tests.rs"] +mod cosign_tests; #[cfg(test)] #[path = "mod_tests.rs"] mod tests; diff --git a/crates/openhuman-core/src/web3/wallet/program/mod_tests.rs b/crates/openhuman-core/src/web3/wallet/program/mod_tests.rs index 3a7b99b3594..52d8d819924 100644 --- a/crates/openhuman-core/src/web3/wallet/program/mod_tests.rs +++ b/crates/openhuman-core/src/web3/wallet/program/mod_tests.rs @@ -7,24 +7,24 @@ use crate::web3::wallet::policy::ExecutionOrigin; use base64::Engine as _; /// `m/44'/501'/1'/0'` of the BIP-39 test phrase (see `ops_tests.rs`). -const SIGNER: &str = "Hh8QwFUA6MtVu1qAoq12ucvFHNwCcVTV7hpWjeY1Hztb"; -const NOW: u64 = 30 * DAY_MS; +pub(super) const SIGNER: &str = "Hh8QwFUA6MtVu1qAoq12ucvFHNwCcVTV7hpWjeY1Hztb"; +pub(super) const NOW: u64 = 30 * DAY_MS; -fn key(text: &str) -> [u8; 32] { +pub(super) fn key(text: &str) -> [u8; 32] { let bytes = bs58::decode(text).into_vec().expect("base58 key"); <[u8; 32]>::try_from(bytes.as_slice()).expect("32-byte key") } -fn filled(byte: u8) -> [u8; 32] { +pub(super) fn filled(byte: u8) -> [u8; 32] { [byte; 32] } /// $TINY, a Token-2022 mint with 6 decimals. const TINY_MINT: &str = "2AF7CqwieUjUPALL7icuZtL3X7wENdjUjGBMmfV2pump"; /// The Solana Foundation Rewards (merkle distributor) program. -const REWARDS_PROGRAM: &str = "REWArDioXgQJ2fZKkfu9LCLjQfRwYWVVfsvcsR5hoXi"; +pub(super) const REWARDS_PROGRAM: &str = "REWArDioXgQJ2fZKkfu9LCLjQfRwYWVVfsvcsR5hoXi"; -fn mint() -> String { +pub(super) fn mint() -> String { TINY_MINT.to_string() } @@ -48,14 +48,14 @@ fn compact(out: &mut Vec, mut value: usize) { /// A test instruction: program key and (key, data) with keys added to the /// message on first use. -struct Ix { - program: [u8; 32], - accounts: Vec<[u8; 32]>, - data: Vec, +pub(super) struct Ix { + pub(super) program: [u8; 32], + pub(super) accounts: Vec<[u8; 32]>, + pub(super) data: Vec, } /// Serialize an unsigned transaction with `signer` as account 0. -fn build( +pub(super) fn build( signer: [u8; 32], required: u8, instructions: &[Ix], @@ -142,7 +142,7 @@ fn ata_create() -> Ix { } } -fn policy() -> WalletPolicyConfig { +pub(super) fn policy() -> WalletPolicyConfig { let mut policy = WalletPolicyConfig::default(); policy.accounts.insert( "solana_1".into(), @@ -167,7 +167,7 @@ fn summary_of(instructions: &[Ix]) -> ProgramTransactionSummary { summarize(&decode_transaction(&tx).unwrap(), SIGNER).unwrap() } -fn refusal_kind(result: Result<(), PolicyRefusal>) -> RefusalKind { +pub(super) fn refusal_kind(result: Result<(), PolicyRefusal>) -> RefusalKind { result.expect_err("expected a refusal").kind } @@ -446,129 +446,6 @@ fn a_transaction_another_key_pays_for_is_refused() { ); } -/// The throwaway `seed` keypair the host generates per Rewards round. -fn seed_key() -> ed25519_dalek::SigningKey { - ed25519_dalek::SigningKey::from_bytes(&[21u8; 32]) -} - -/// Rewards `CreateMerkleDistribution` (ix 5): signers are the payer and -/// authority (both the index-1 account) and the seed; it funds the vault from -/// the account's TINY token account by a Token-2022 CPI. -fn create_distribution() -> Ix { - Ix { - program: key(REWARDS_PROGRAM), - accounts: vec![ - seed_key().verifying_key().to_bytes(), - key(SIGNER), - filled(3), - filled(1), - key(&mint()), - key(TOKEN_2022_PROGRAM), - key(SYSTEM_PROGRAM), - ], - data: vec![5, 0xaa], - } -} - -/// `tx` with signature slot `slot` set to `signature`. -fn with_signature(tx: &[u8], slot: usize, signature: &[u8; 64]) -> Vec { - let decoded = decode_transaction(tx).unwrap(); - let mut out = tx.to_vec(); - let at = decoded.signatures_offset + slot * 64; - out[at..at + 64].copy_from_slice(signature); - out -} - -fn seed_signed(tx: &[u8]) -> Vec { - use ed25519_dalek::Signer as _; - let message = decode_transaction(tx).unwrap().message; - with_signature(tx, 1, &seed_key().sign(&message).to_bytes()) -} - -#[test] -fn a_co_signed_rewards_distribution_is_accepted_once_the_seed_has_signed() { - let unsigned = build(key(SIGNER), 2, &[create_distribution()], None); - let decoded = decode_transaction(&unsigned).unwrap(); - assert_eq!( - base58(&decoded.account_keys[1]), - base58(&seed_key().verifying_key().to_bytes()) - ); - // The seed has not signed yet. - let refused = summarize(&decoded, SIGNER).unwrap_err(); - assert_eq!(refused.kind, RefusalKind::TransactionNotAllowed); - assert!( - refused.message.contains("has not signed"), - "{}", - refused.message - ); - - let signed = seed_signed(&unsigned); - let summary = summarize(&decode_transaction(&signed).unwrap(), SIGNER).unwrap(); - assert_eq!(summary.signers.len(), 2); - assert_eq!(summary.signers[0], SIGNER); - assert_eq!(summary.programs, vec![REWARDS_PROGRAM.to_string()]); - // The vault is funded by CPI: nothing visible, so the declared debit is - // what the caps (1000 per transaction) apply to. - assert!(summary.totals.is_empty()); - let check = - |debits: &[MintTotal]| evaluate_program(&policy(), "solana", 1, &summary, debits, &[], NOW); - assert_eq!(check(&declared(&mint(), 1_000)), Ok(())); - assert_eq!( - refusal_kind(check(&declared(&mint(), 5_000))), - RefusalKind::PerTransaction - ); -} - -#[test] -fn a_co_signature_that_does_not_verify_is_refused() { - let unsigned = build(key(SIGNER), 2, &[create_distribution()], None); - // Signed over other bytes, and garbage. - let other = { - use ed25519_dalek::Signer as _; - seed_key().sign(b"something else").to_bytes() - }; - for signature in [other, [0x11; 64]] { - let tx = with_signature(&unsigned, 1, &signature); - let refused = summarize(&decode_transaction(&tx).unwrap(), SIGNER).unwrap_err(); - assert_eq!(refused.kind, RefusalKind::TransactionNotAllowed); - assert!( - refused.message.contains("does not verify"), - "{}", - refused.message - ); - } -} - -#[test] -fn the_accounts_signature_fills_its_own_slot_and_completes_the_transaction() { - use ed25519_dalek::Signer as _; - let tx = seed_signed(&build(key(SIGNER), 2, &[create_distribution()], None)); - let decoded = decode_transaction(&tx).unwrap(); - // Stand-in for the module: any key's signature lands in the account's slot. - let ours = ed25519_dalek::SigningKey::from_bytes(&[33u8; 32]); - let signature = ours.sign(&decoded.message).to_bytes(); - let signed = attach_signature(&tx, &decoded, &key(SIGNER), &signature).unwrap(); - let after = decode_transaction(&signed).unwrap(); - assert_eq!(after.signatures[0], signature); - assert_eq!( - after.signatures[1], decoded.signatures[1], - "the seed's stays" - ); - assert_eq!(after.message, decoded.message); - assert!(signature_is_valid( - &key(&base58(&seed_key().verifying_key().to_bytes())), - &after.message, - &after.signatures[1] - )); - assert!(signature_is_valid( - &ours.verifying_key().to_bytes(), - &after.message, - &after.signatures[0] - )); - // A key holding no signer slot cannot be placed. - assert!(attach_signature(&tx, &decoded, &filled(3), &signature).is_err()); -} - #[test] fn address_lookup_tables_are_refused() { let tx = build(key(SIGNER), 1, &[distributor_call()], Some(1)); @@ -694,7 +571,7 @@ async fn execute_refuses_an_unknown_quote() { assert!(!has_quote_for_test("prog-missing")); } -fn declared(mint: &str, amount: u64) -> Vec { +pub(super) fn declared(mint: &str, amount: u64) -> Vec { vec![MintTotal { mint: mint.to_string(), amount_raw: amount.to_string(),