From 81363f9cf5197e73b0d0c0e5b4f336ee57410952 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Mon, 16 Nov 2026 07:02:26 +0000 Subject: [PATCH 1/5] fix(wallet): reject primary accounts that alias a secondary path Wallet setup now refuses an index-0 account whose derivation path matches a known secondary account, since that primary would resolve to the same key and let the secondary's program policy sign for it. Stored wallets written before this check are quarantined at load time so they can never sign as the secondary. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- crates/openhuman-core/src/web3/wallet/ops.rs | 12 +++++ .../src/web3/wallet/ops_tests.rs | 47 +++++++++++++++++++ 2 files changed, 59 insertions(+) diff --git a/crates/openhuman-core/src/web3/wallet/ops.rs b/crates/openhuman-core/src/web3/wallet/ops.rs index 7d983973126..9c5777db0a4 100644 --- a/crates/openhuman-core/src/web3/wallet/ops.rs +++ b/crates/openhuman-core/src/web3/wallet/ops.rs @@ -263,6 +263,18 @@ fn validate_setup(params: &WalletSetupParams) -> Result, Stri account.chain.as_str() )); } + if account.index == 0 + && SECONDARY_ACCOUNTS.iter().any(|secondary| { + secondary.chain == account.chain && secondary.derivation_path == derivation_path + }) + { + // A primary at a secondary path resolves to that secondary account's + // key, so the secondary's program policy would sign for the primary. + return Err(format!( + "wallet setup account '{}' index 0 uses a secondary account path; a primary account must not alias one", + 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. diff --git a/crates/openhuman-core/src/web3/wallet/ops_tests.rs b/crates/openhuman-core/src/web3/wallet/ops_tests.rs index a7dfd288bd9..4bf413b96fe 100644 --- a/crates/openhuman-core/src/web3/wallet/ops_tests.rs +++ b/crates/openhuman-core/src/web3/wallet/ops_tests.rs @@ -453,3 +453,50 @@ async fn secret_material_resolves_the_secondary_path_for_a_wallet_that_predates_ crate::web3::wallet::test_support::sample_solana_address() ); } + +#[test] +fn validate_setup_rejects_a_primary_at_a_secondary_path() { + // An index-0 account at the giveaway path would resolve to the same key + // as index 1, so the secondary program policy would sign for the primary. + let mut params = sample_params(); + let mut alias = sample_account(WalletChain::Solana); + alias.derivation_path = giveaway_account().derivation_path; + params.accounts.retain(|account| account.chain != WalletChain::Solana); + params.accounts.push(alias); + assert!(validate_setup(¶ms) + .expect_err("primary aliasing the secondary path") + .contains("secondary account path")); +} + +#[tokio::test] +async fn a_stored_primary_at_the_secondary_path_is_quarantined_before_signing() { + // A wallet state written with its Solana primary on the giveaway path (by a + // build that did not refuse it) must not sign for index 1: load validation + // quarantines it, so no secondary key is ever resolved from 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::set_workspace_env_for_test(&temp).await; + let config = ctx.load_config().await.expect("config"); + { + let mut state = stored_state(); + state.accounts = WalletChain::ALL + .into_iter() + .map(crate::web3::wallet::test_support::sample_account) + .collect(); + for account in state.accounts.iter_mut() { + if account.chain == WalletChain::Solana { + account.derivation_path = giveaway_account().derivation_path; + } + } + let _guard = WALLET_STATE_FILE_LOCK.lock(); + save_stored_wallet_state_unlocked(&config, &state).expect("save state"); + } + let error = secret_material(&ctx, WalletChain::Solana, 1) + .await + .expect_err("an aliased primary must not sign as the secondary"); + assert_eq!(error, WALLET_NOT_CONFIGURED_MESSAGE); + assert!(load_stored_wallet_state_unlocked(&config) + .expect("load") + .is_none()); +} From cdc918c5a6b1df7da755a1dcd19d16cf73f76056 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Mon, 16 Nov 2026 07:02:39 +0000 Subject: [PATCH 2/5] fix(wallet): measure program debits from one simulation slot The pre-state (getTokenAccountsByOwner) and post-state (simulateTransaction) were read separately, so a deposit between them could hide a token debit. Every RPC answer now carries its context slot; a measurement whose reads disagree is repeated and then refused. Only token accounts named in the transaction's account keys are read or requested, which also avoids the RPC rejecting an address list longer than the account-key list. Co-authored-by: Medulla --- .../src/web3/wallet/program/simulate.rs | 75 +++++++++++++-- .../src/web3/wallet/program/simulate_tests.rs | 94 ++++++++++++++++++- 2 files changed, 160 insertions(+), 9 deletions(-) diff --git a/crates/openhuman-core/src/web3/wallet/program/simulate.rs b/crates/openhuman-core/src/web3/wallet/program/simulate.rs index 117f86f5493..ab2ce32ed5d 100644 --- a/crates/openhuman-core/src/web3/wallet/program/simulate.rs +++ b/crates/openhuman-core/src/web3/wallet/program/simulate.rs @@ -6,18 +6,23 @@ //! 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. +//! Token-2022, gives the signer's token accounts that the transaction +//! names, and their balances 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. //! +//! The pre-state and the post-state are only comparable when they come from +//! the same bank. Every answer carries the slot it was computed at, and a +//! measurement whose reads disagree on the slot is repeated, then refused. +//! //! [`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 std::collections::{BTreeMap, BTreeSet}; use base64::Engine as _; use serde::{Deserialize, Serialize}; @@ -29,6 +34,10 @@ 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; +/// How many times a measurement whose reads came from different slots is +/// repeated before the transaction is refused. +const SNAPSHOT_ATTEMPTS: usize = 3; + /// What the simulation showed. #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] @@ -155,18 +164,61 @@ fn account_data(account: &Value) -> Option> { .ok() } -/// Read the signer's token accounts, simulate `transaction` and measure the -/// debits, over the Solana JSON-RPC at `url`. +/// The slot an RPC answer was computed at (`result.context.slot`). +fn context_slot(answer: &Value, method: &str) -> Result { + answer + .get("context") + .and_then(|context| context.get("slot")) + .and_then(Value::as_u64) + .ok_or_else(|| format!("{method} returned no context slot")) +} + +/// One measurement: the report, or the slots its reads came from when they +/// disagree (the pre-state and post-state are then not comparable). +enum Attempt { + Measured(SimulationReport), + SplitAcrossSlots(Vec), +} + +/// Read the signer's token accounts that `account_keys` names, simulate +/// `transaction` and measure the debits, over the Solana JSON-RPC at `url`. +/// +/// Only accounts named in the transaction's own account keys are read or +/// requested: a transaction cannot write an account it does not name, so +/// the rest cannot be debited and need not be measured. /// /// # Errors /// -/// A transport or RPC error, or an answer that is not the documented shape. +/// A transport or RPC error, an answer that is not the documented shape, or +/// reads that stay split across slots after [`SNAPSHOT_ATTEMPTS`] attempts. pub async fn simulate( url: &str, transaction: &[u8], owner: &[u8; 32], + account_keys: &[[u8; 32]], ) -> Result { + let mut seen = Vec::new(); + for _ in 0..SNAPSHOT_ATTEMPTS { + match measure(url, transaction, owner, account_keys).await? { + Attempt::Measured(report) => return Ok(report), + Attempt::SplitAcrossSlots(slots) => seen = slots, + } + } + Err(format!( + "the token balances and the simulation were read at different slots ({seen:?}) \ + on every attempt; the transaction was not measured, retry" + )) +} + +async fn measure( + url: &str, + transaction: &[u8], + owner: &[u8; 32], + account_keys: &[[u8; 32]], +) -> Result { let owner_text = base58(owner); + let named: BTreeSet = account_keys.iter().map(|key| base58(key)).collect(); + let mut slots = Vec::with_capacity(3); let mut addresses = Vec::new(); let mut pre = Vec::new(); for program in [TOKEN_PROGRAM, TOKEN_2022_PROGRAM] { @@ -180,6 +232,7 @@ pub async fn simulate( ]), ) .await?; + slots.push(context_slot(&answer, "getTokenAccountsByOwner")?); let rows = answer .get("value") .and_then(Value::as_array) @@ -189,6 +242,9 @@ pub async fn simulate( .get("pubkey") .and_then(Value::as_str) .ok_or("getTokenAccountsByOwner row has no pubkey")?; + if !named.contains(pubkey) { + continue; + } let state = row .get("account") .and_then(account_data) @@ -214,6 +270,11 @@ pub async fn simulate( ]), ) .await?; + slots.push(context_slot(&answer, "simulateTransaction")?); + if slots.iter().any(|slot| *slot != slots[0]) { + tracing::warn!(?slots, "{} token reads and the simulation were not at one slot", super::LOG_PREFIX); + return Ok(Attempt::SplitAcrossSlots(slots)); + } let value = answer .get("value") .ok_or("simulateTransaction returned no value")?; @@ -230,7 +291,7 @@ pub async fn simulate( if err.is_none() && post.len() != pre.len() { return Err("simulateTransaction returned the wrong number of accounts".to_string()); } - Ok(SimulationReport { + Ok(Attempt::Measured(SimulationReport { debits: if err.is_some() { Vec::new() } else { @@ -239,7 +300,7 @@ pub async fn simulate( err, token_accounts: addresses, units_consumed: value.get("unitsConsumed").and_then(Value::as_u64), - }) + })) } #[cfg(test)] 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 7730bf9027a..75b5afd29d0 100644 --- a/crates/openhuman-core/src/web3/wallet/program/simulate_tests.rs +++ b/crates/openhuman-core/src/web3/wallet/program/simulate_tests.rs @@ -147,7 +147,7 @@ async fn simulate_reads_the_owners_token_accounts_and_measures_the_cpi_debit() { }))) .respond_with(ResponseTemplate::new(200).set_body_json(json!({ "jsonrpc": "2.0", "id": 1, - "result": {"context": {"slot": 2}, "value": { + "result": {"context": {"slot": 1}, "value": { "err": null, "logs": [], "unitsConsumed": 42_000, @@ -157,7 +157,7 @@ async fn simulate_reads_the_owners_token_accounts_and_measures_the_cpi_debit() { .mount(&server) .await; - let report = simulate(&server.uri(), &[1, 2, 3], &key(SIGNER)) + let report = simulate(&server.uri(), &[1, 2, 3], &key(SIGNER), &[key(vault_source)]) .await .expect("simulation"); assert_eq!(report.err, None); @@ -170,3 +170,93 @@ async fn simulate_reads_the_owners_token_accounts_and_measures_the_cpi_debit() { ); assert!(check_simulation(&[total(TINY_MINT, 999_999)], &report).is_err()); } + +/// The signer's token accounts for `program`, as `getTokenAccountsByOwner` +/// answers them, at `slot`. +fn owner_accounts(program: &str, rows: Value, slot: u64) -> Mock { + Mock::given(method("POST")) + .and(body_partial_json(json!({ + "method": "getTokenAccountsByOwner", + "params": [SIGNER, {"programId": program}] + }))) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({ + "jsonrpc": "2.0", "id": 1, + "result": {"context": {"slot": slot}, "value": rows} + }))) +} + +#[tokio::test] +async fn a_measurement_whose_reads_span_slots_is_refused() { + // The signer's balance is read at slot 1, then the simulation runs at + // slot 2: a deposit between the two would hide a debit, so nothing is + // measured from that pair. + let server = MockServer::start().await; + let vault_source = "Source1111111111111111111111111111111111111"; + owner_accounts( + TOKEN_2022_PROGRAM, + json!([{"pubkey": vault_source, "account": {"data": encoded(&token_account(TINY_MINT, SIGNER, 1_000_000))}}]), + 1, + ) + .mount(&server) + .await; + owner_accounts(TOKEN_PROGRAM, json!([]), 1).mount(&server).await; + Mock::given(method("POST")) + .and(body_partial_json(json!({"method": "simulateTransaction"}))) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({ + "jsonrpc": "2.0", "id": 1, + "result": {"context": {"slot": 2}, "value": { + "err": null, "logs": [], + "accounts": [{"data": encoded(&token_account(TINY_MINT, SIGNER, 900_000))}] + }} + }))) + .mount(&server) + .await; + + let error = simulate(&server.uri(), &[1, 2, 3], &key(SIGNER), &[key(vault_source)]) + .await + .expect_err("split slots must not be measured"); + assert!(error.contains("different slots"), "{error}"); +} + +#[tokio::test] +async fn only_token_accounts_the_transaction_names_are_read_or_requested() { + // The signer also holds an unrelated account the transaction never names. + // Requesting it would be rejected by the RPC when it has more addresses + // than the transaction has account keys, and it cannot be debited anyway. + let server = MockServer::start().await; + let vault_source = "Source1111111111111111111111111111111111111"; + let unrelated = "Other11111111111111111111111111111111111111"; + owner_accounts( + TOKEN_2022_PROGRAM, + json!([ + {"pubkey": vault_source, "account": {"data": encoded(&token_account(TINY_MINT, SIGNER, 5_000_000))}}, + {"pubkey": unrelated, "account": {"data": encoded(&token_account(TINY_MINT, SIGNER, 42))}} + ]), + 1, + ) + .mount(&server) + .await; + owner_accounts(TOKEN_PROGRAM, json!([]), 1).mount(&server).await; + Mock::given(method("POST")) + .and(body_partial_json(json!({ + "method": "simulateTransaction", + "params": [base64::engine::general_purpose::STANDARD.encode([1u8, 2, 3]), { + "accounts": {"encoding": "base64", "addresses": [vault_source]} + }] + }))) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({ + "jsonrpc": "2.0", "id": 1, + "result": {"context": {"slot": 1}, "value": { + "err": null, "logs": [], + "accounts": [{"data": encoded(&token_account(TINY_MINT, SIGNER, 4_000_000))}] + }} + }))) + .mount(&server) + .await; + + let report = simulate(&server.uri(), &[1, 2, 3], &key(SIGNER), &[key(vault_source)]) + .await + .expect("the request names only the transaction's account"); + assert_eq!(report.token_accounts, vec![vault_source.to_string()]); + assert_eq!(report.debits, vec![total(TINY_MINT, 1_000_000)]); +} From 7269e4ec7423229da631cc05f10bddeceb339919 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Mon, 16 Nov 2026 07:02:43 +0000 Subject: [PATCH 3/5] fix(wallet): bind program quotes to their context and refuse late execution The quote map is process-wide, so a quote prepared in one workspace or wallet could be executed, and spend its allowance, in another. A quote now records its workspace, a hash of the encrypted phrase, its account index and the Solana endpoint, and is taken only under the same binding; a mismatched take leaves it in place. Execution also reads the clock at the reservation point and refuses a quote that expired while it was being re-simulated, before anything is signed. The snapshot comment now states what the caps guarantee. Co-authored-by: Medulla --- .../openhuman-core/src/web3/wallet/policy.rs | 2 + .../src/web3/wallet/program/ops.rs | 101 +++++++++++++++--- .../src/web3/wallet/program/ops_tests.rs | 85 +++++++++++++++ 3 files changed, 171 insertions(+), 17 deletions(-) create mode 100644 crates/openhuman-core/src/web3/wallet/program/ops_tests.rs diff --git a/crates/openhuman-core/src/web3/wallet/policy.rs b/crates/openhuman-core/src/web3/wallet/policy.rs index 7069f20e292..2ea15a78789 100644 --- a/crates/openhuman-core/src/web3/wallet/policy.rs +++ b/crates/openhuman-core/src/web3/wallet/policy.rs @@ -165,6 +165,8 @@ pub enum RefusalKind { /// The declared token debits disagree with what the transaction moves /// (its visible transfers, or its simulation), or the simulation failed. SimulationMismatch, + /// The prepared quote reached its expiry before it could be signed. + QuoteExpired, } /// A refused execute. diff --git a/crates/openhuman-core/src/web3/wallet/program/ops.rs b/crates/openhuman-core/src/web3/wallet/program/ops.rs index a365603dbef..a7b3d46b824 100644 --- a/crates/openhuman-core/src/web3/wallet/program/ops.rs +++ b/crates/openhuman-core/src/web3/wallet/program/ops.rs @@ -6,6 +6,7 @@ use std::sync::Mutex; use base64::Engine as _; use once_cell::sync::Lazy; +use sha2::{Digest, Sha256}; use serde::{Deserialize, Serialize}; use tinywallet_bus::wire::{RpcEndpointKey, RpcSource, Scheme, SecretMaterial, Signature}; use zeroize::Zeroizing; @@ -82,11 +83,25 @@ pub struct ExecuteProgramParams { pub quote_id: String, } +/// What a quote is bound to. The quote map is process-wide, so a quote can be +/// taken only by the context it was prepared in: the same workspace (whose +/// spend ledger it draws on), the same wallet (a hash of the encrypted phrase, +/// which changes when the wallet is replaced), the same account and the same +/// Solana endpoint. +#[derive(Debug, Clone, PartialEq, Eq)] +struct QuoteBinding { + workspace: std::path::PathBuf, + wallet: String, + account_index: u32, + endpoint: String, +} + #[derive(Clone)] struct StoredQuote { prepared: PreparedProgram, transaction: Vec, decoded: DecodedTransaction, + binding: QuoteBinding, } static QUOTES: Lazy>> = Lazy::new(|| Mutex::new(HashMap::new())); @@ -98,8 +113,48 @@ fn store_quote(quote: StoredQuote, now_ms: u64) { } } -fn take_quote(quote_id: &str) -> Option { - QUOTES.lock().ok()?.remove(quote_id) +/// Remove the quote only when `binding` matches the one it was prepared under. +/// A mismatched request leaves the quote where it is, for its own context. +fn take_quote(quote_id: &str, binding: &QuoteBinding) -> Option { + let mut quotes = QUOTES.lock().ok()?; + if quotes.get(quote_id)?.binding != *binding { + return None; + } + quotes.remove(quote_id) +} + +/// Whether a quote with this id is held, in any context. +fn quote_held(quote_id: &str) -> bool { + QUOTES + .lock() + .is_ok_and(|quotes| quotes.contains_key(quote_id)) +} + +/// The context a quote for `account_index` is bound to, read now. +async fn quote_binding( + ctx: &DispatchCtx, + config: &crate::config::Config, + account_index: u32, +) -> Result { + let material = + super::super::ops::secret_material(ctx, WalletChain::Solana, account_index).await?; + Ok(QuoteBinding { + workspace: config.workspace_dir.clone(), + wallet: hex::encode(Sha256::digest(material.encrypted_mnemonic.as_bytes())), + account_index, + endpoint: solana_rpc_url(ctx).await?, + }) +} + +/// A quote is usable strictly before its expiry instant. +fn ensure_unexpired(expires_at_ms: u64, now_ms: u64) -> Result<(), PolicyRefusal> { + if expires_at_ms > now_ms { + return Ok(()); + } + Err(refusal( + RefusalKind::QuoteExpired, + format!("the quote expired at {expires_at_ms} (now {now_ms}); prepare it again"), + )) } /// Prepare quotes currently held (test support). @@ -155,6 +210,7 @@ pub async fn prepare_program( .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 binding = quote_binding(ctx, &config, 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)?; @@ -197,6 +253,7 @@ pub async fn prepare_program( prepared: prepared.clone(), transaction, decoded, + binding, }, now, ); @@ -262,23 +319,24 @@ pub async fn execute_prepared_program( ) -> 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 unavailable = || "prepared program quote is unavailable or expired".to_string(); + if !quote_held(¶ms.quote_id) { + return Err(unavailable()); } + // A quote from another workspace, wallet, account or endpoint is reported + // as unavailable and stays in the map for its own context. + let binding = quote_binding(ctx, &config, params.account_index).await?; + let stored = take_quote(¶ms.quote_id, &binding) + .filter(|stored| stored.prepared.expires_at_ms > now) + .ok_or_else(unavailable)?; let origin = ExecutionOrigin::rpc(); 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. + // Simulate against the chain as it is now. The caps and the declaration + // are checked against this snapshot only: an opaque program can debit a + // different amount when the transaction is included, so the caps are + // not a bound on the chain's final state. let simulated = match simulate_quote(ctx, &stored.transaction, &stored.decoded).await { Ok(report) => check_simulation(&prepared.declared_debits, &report), Err(error) => { @@ -288,9 +346,14 @@ pub async fn execute_prepared_program( }; let reserved = ledger .reserve(|records| { + // Read the clock at the point of no return. The simulation above + // can take many seconds, so a quote that expired while it ran must + // be refused here, before anything is signed. + let reserved_at = super::super::policy::wall_clock_ms(); if let Some(refused) = origin_refusal(&origin) { return Err(refused); } + ensure_unexpired(prepared.expires_at_ms, reserved_at)?; simulated.clone()?; if let Some(earlier) = records.iter().rev().find(|record| { record.quote_id == prepared.quote_id && record.status.counts_against_caps() @@ -310,13 +373,13 @@ pub async fn execute_prepared_program( &prepared.summary, &prepared.declared_debits, records, - now, + reserved_at, )?; Ok(program_record( &prepared, &origin, LedgerStatus::Pending, - now, + reserved_at, )) }) .map_err(|error| format!("wallet spend ledger is unavailable: {error:#}"))?; @@ -469,7 +532,11 @@ async fn simulate_quote( .first() .ok_or_else(|| "the transaction lists no accounts".to_string())?; let url = solana_rpc_url(ctx).await?; - simulate(&url, transaction, owner) + simulate(&url, transaction, owner, &decoded.account_keys) .await .map_err(|error| format!("could not simulate the transaction: {error}")) } + +#[cfg(test)] +#[path = "ops_tests.rs"] +mod tests; diff --git a/crates/openhuman-core/src/web3/wallet/program/ops_tests.rs b/crates/openhuman-core/src/web3/wallet/program/ops_tests.rs new file mode 100644 index 00000000000..b3c89d862e9 --- /dev/null +++ b/crates/openhuman-core/src/web3/wallet/program/ops_tests.rs @@ -0,0 +1,85 @@ +use super::*; + +fn binding(workspace: &str, wallet: &str, account_index: u32, endpoint: &str) -> QuoteBinding { + QuoteBinding { + workspace: std::path::PathBuf::from(workspace), + wallet: wallet.to_string(), + account_index, + endpoint: endpoint.to_string(), + } +} + +fn stored(quote_id: &str, binding: QuoteBinding) -> StoredQuote { + StoredQuote { + prepared: PreparedProgram { + quote_id: quote_id.to_string(), + chain: WalletChain::Solana, + account_index: binding.account_index, + address: String::new(), + summary: ProgramTransactionSummary { + fee_payer: String::new(), + signers: Vec::new(), + recent_blockhash: String::new(), + programs: Vec::new(), + instructions: Vec::new(), + movements: Vec::new(), + totals: Vec::new(), + }, + declared_debits: Vec::new(), + simulation: SimulationReport::default(), + created_at_ms: 0, + expires_at_ms: u64::MAX, + }, + transaction: Vec::new(), + decoded: DecodedTransaction { + signature_count: 0, + signatures_offset: 0, + signatures: Vec::new(), + message: Vec::new(), + versioned: false, + num_required_signatures: 0, + account_keys: Vec::new(), + recent_blockhash: [0; 32], + instructions: Vec::new(), + lookup_table_count: 0, + }, + binding, + } +} + +#[test] +fn a_quote_is_taken_only_in_the_context_it_was_prepared_in() { + // The quote map is process-wide: another workspace, wallet, account or + // endpoint must not be able to spend this quote, and a refused take must + // leave it in place for its own context. + let id = format!("test-quote-{}", uuid::Uuid::new_v4()); + let prepared_in = binding("/ws/a", "wallet-1", 1, "https://rpc.a"); + store_quote(stored(&id, prepared_in.clone()), 0); + + let other_contexts = [ + binding("/ws/b", "wallet-1", 1, "https://rpc.a"), + binding("/ws/a", "wallet-2", 1, "https://rpc.a"), + binding("/ws/a", "wallet-1", 0, "https://rpc.a"), + binding("/ws/a", "wallet-1", 1, "https://rpc.b"), + ]; + for other in &other_contexts { + assert!(take_quote(&id, other).is_none(), "taken under {other:?}"); + } + assert!(has_quote_for_test(&id), "a refused take must keep the quote"); + + let taken = take_quote(&id, &prepared_in).expect("the preparing context takes it"); + assert_eq!(taken.binding, prepared_in); + assert!(!has_quote_for_test(&id), "a taken quote is removed"); +} + +#[test] +fn a_quote_is_refused_from_its_expiry_instant_onward() { + assert!(ensure_unexpired(1_000, 999).is_ok()); + assert_eq!( + ensure_unexpired(1_000, 1_000) + .expect_err("the expiry instant is already too late") + .kind, + RefusalKind::QuoteExpired + ); + assert!(ensure_unexpired(1_000, 1_001).is_err()); +} From 2a73b4a04c42eb5d587d4ee6e1291a56c7a3013a Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Mon, 16 Nov 2026 07:02:44 +0000 Subject: [PATCH 4/5] chore(ci): register the program quote store in process statics The quote map is a new process static. It is partitioned by QuoteBinding and the record names the test that pins that partition. Co-authored-by: Medulla --- scripts/ci/process-statics.json | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/scripts/ci/process-statics.json b/scripts/ci/process-statics.json index 440a2a8c104..8bccf108dbf 100644 --- a/scripts/ci/process-statics.json +++ b/scripts/ci/process-statics.json @@ -948,5 +948,15 @@ "category": "A", "reason": "Host wiring: an id-keyed table of picture sinks the embedding host registers at startup (core::slots::HookSlot). It holds code, never tenant data; the pictures pass through and are not kept.", "verification": "modules/browser_pictures_tests.rs: a_registered_sink_gets_each_picture_and_a_refusal_is_not_fatal" + }, + { + "file": "crates/openhuman-core/src/web3/wallet/program/ops.rs", + "scope": "", + "name": "QUOTES", + "type": "Lazy>>", + "count": 1, + "category": "B", + "reason": "Prepared program quotes are partitioned by QuoteBinding (workspace path, a hash of the encrypted phrase, account index and Solana endpoint). A take is refused, and the quote stays in the map, unless all four match the context that takes it.", + "verification": "web3/wallet/program/ops_tests.rs: a_quote_is_taken_only_in_the_context_it_was_prepared_in" } ] From cdd4c450b96a25cd3669921f735f527f6ebb48ce Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Mon, 16 Nov 2026 07:11:28 +0000 Subject: [PATCH 5/5] style(web3): reformat wallet program sources with rustfmt Applied rustfmt formatting across the wallet program ops and simulate modules and their tests, wrapping long call sites, assertions, and log macros. No behaviour changed. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../src/web3/wallet/ops_tests.rs | 4 +- .../src/web3/wallet/program/ops.rs | 2 +- .../src/web3/wallet/program/ops_tests.rs | 5 ++- .../src/web3/wallet/program/simulate.rs | 6 ++- .../src/web3/wallet/program/simulate_tests.rs | 41 ++++++++++++++----- 5 files changed, 43 insertions(+), 15 deletions(-) diff --git a/crates/openhuman-core/src/web3/wallet/ops_tests.rs b/crates/openhuman-core/src/web3/wallet/ops_tests.rs index 4bf413b96fe..92af978a376 100644 --- a/crates/openhuman-core/src/web3/wallet/ops_tests.rs +++ b/crates/openhuman-core/src/web3/wallet/ops_tests.rs @@ -461,7 +461,9 @@ fn validate_setup_rejects_a_primary_at_a_secondary_path() { let mut params = sample_params(); let mut alias = sample_account(WalletChain::Solana); alias.derivation_path = giveaway_account().derivation_path; - params.accounts.retain(|account| account.chain != WalletChain::Solana); + params + .accounts + .retain(|account| account.chain != WalletChain::Solana); params.accounts.push(alias); assert!(validate_setup(¶ms) .expect_err("primary aliasing the secondary path") diff --git a/crates/openhuman-core/src/web3/wallet/program/ops.rs b/crates/openhuman-core/src/web3/wallet/program/ops.rs index a7b3d46b824..5ad13e7dce9 100644 --- a/crates/openhuman-core/src/web3/wallet/program/ops.rs +++ b/crates/openhuman-core/src/web3/wallet/program/ops.rs @@ -6,8 +6,8 @@ use std::sync::Mutex; use base64::Engine as _; use once_cell::sync::Lazy; -use sha2::{Digest, Sha256}; use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; use tinywallet_bus::wire::{RpcEndpointKey, RpcSource, Scheme, SecretMaterial, Signature}; use zeroize::Zeroizing; diff --git a/crates/openhuman-core/src/web3/wallet/program/ops_tests.rs b/crates/openhuman-core/src/web3/wallet/program/ops_tests.rs index b3c89d862e9..5e0cbfcbf8c 100644 --- a/crates/openhuman-core/src/web3/wallet/program/ops_tests.rs +++ b/crates/openhuman-core/src/web3/wallet/program/ops_tests.rs @@ -65,7 +65,10 @@ fn a_quote_is_taken_only_in_the_context_it_was_prepared_in() { for other in &other_contexts { assert!(take_quote(&id, other).is_none(), "taken under {other:?}"); } - assert!(has_quote_for_test(&id), "a refused take must keep the quote"); + assert!( + has_quote_for_test(&id), + "a refused take must keep the quote" + ); let taken = take_quote(&id, &prepared_in).expect("the preparing context takes it"); assert_eq!(taken.binding, prepared_in); diff --git a/crates/openhuman-core/src/web3/wallet/program/simulate.rs b/crates/openhuman-core/src/web3/wallet/program/simulate.rs index ab2ce32ed5d..7e103cae3e3 100644 --- a/crates/openhuman-core/src/web3/wallet/program/simulate.rs +++ b/crates/openhuman-core/src/web3/wallet/program/simulate.rs @@ -272,7 +272,11 @@ async fn measure( .await?; slots.push(context_slot(&answer, "simulateTransaction")?); if slots.iter().any(|slot| *slot != slots[0]) { - tracing::warn!(?slots, "{} token reads and the simulation were not at one slot", super::LOG_PREFIX); + tracing::warn!( + ?slots, + "{} token reads and the simulation were not at one slot", + super::LOG_PREFIX + ); return Ok(Attempt::SplitAcrossSlots(slots)); } let value = answer 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 75b5afd29d0..50579401b31 100644 --- a/crates/openhuman-core/src/web3/wallet/program/simulate_tests.rs +++ b/crates/openhuman-core/src/web3/wallet/program/simulate_tests.rs @@ -157,9 +157,14 @@ async fn simulate_reads_the_owners_token_accounts_and_measures_the_cpi_debit() { .mount(&server) .await; - let report = simulate(&server.uri(), &[1, 2, 3], &key(SIGNER), &[key(vault_source)]) - .await - .expect("simulation"); + let report = simulate( + &server.uri(), + &[1, 2, 3], + &key(SIGNER), + &[key(vault_source)], + ) + .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()]); @@ -199,7 +204,9 @@ async fn a_measurement_whose_reads_span_slots_is_refused() { ) .mount(&server) .await; - owner_accounts(TOKEN_PROGRAM, json!([]), 1).mount(&server).await; + owner_accounts(TOKEN_PROGRAM, json!([]), 1) + .mount(&server) + .await; Mock::given(method("POST")) .and(body_partial_json(json!({"method": "simulateTransaction"}))) .respond_with(ResponseTemplate::new(200).set_body_json(json!({ @@ -212,9 +219,14 @@ async fn a_measurement_whose_reads_span_slots_is_refused() { .mount(&server) .await; - let error = simulate(&server.uri(), &[1, 2, 3], &key(SIGNER), &[key(vault_source)]) - .await - .expect_err("split slots must not be measured"); + let error = simulate( + &server.uri(), + &[1, 2, 3], + &key(SIGNER), + &[key(vault_source)], + ) + .await + .expect_err("split slots must not be measured"); assert!(error.contains("different slots"), "{error}"); } @@ -236,7 +248,9 @@ async fn only_token_accounts_the_transaction_names_are_read_or_requested() { ) .mount(&server) .await; - owner_accounts(TOKEN_PROGRAM, json!([]), 1).mount(&server).await; + owner_accounts(TOKEN_PROGRAM, json!([]), 1) + .mount(&server) + .await; Mock::given(method("POST")) .and(body_partial_json(json!({ "method": "simulateTransaction", @@ -254,9 +268,14 @@ async fn only_token_accounts_the_transaction_names_are_read_or_requested() { .mount(&server) .await; - let report = simulate(&server.uri(), &[1, 2, 3], &key(SIGNER), &[key(vault_source)]) - .await - .expect("the request names only the transaction's account"); + let report = simulate( + &server.uri(), + &[1, 2, 3], + &key(SIGNER), + &[key(vault_source)], + ) + .await + .expect("the request names only the transaction's account"); assert_eq!(report.token_accounts, vec![vault_source.to_string()]); assert_eq!(report.debits, vec![total(TINY_MINT, 1_000_000)]); }