diff --git a/Cargo.lock b/Cargo.lock index 6b8af974616..c56a15d7bb9 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5684,12 +5684,14 @@ dependencies = [ "async-trait", "axum", "base64 0.22.1", + "bs58", "bytes", "chrono", "chrono-tz", "directories", "dirs 6.0.0", "dotenvy", + "ed25519-dalek", "env_logger", "flate2", "fs2", 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/Cargo.toml b/crates/openhuman-core/Cargo.toml index fb762a4df26..6a03db7e91b 100644 --- a/crates/openhuman-core/Cargo.toml +++ b/crates/openhuman-core/Cargo.toml @@ -452,6 +452,13 @@ 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 } +# 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] @@ -721,6 +728,8 @@ voice = [ # feature carries only the lightweight bus contract and generic HTTP client. web3 = [ "dep:tinywallet-bus", + "dep:bs58", + "dep:ed25519-dalek", "modules", ] 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..f303b68ce1c 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 = [ +//! "TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb", # Token-2022 +//! "ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL", # Associated Token Account +//! "", # the program being called +//! ] +//! +//! [[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,53 @@ 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 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 { + /// 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; 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..e6b782d2521 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,51 @@ 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/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/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/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..a0aacdf2284 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,37 @@ 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, 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 +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 +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/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/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/mod.rs b/crates/openhuman-core/src/web3/wallet/mod.rs index f336d8d3ff8..5b12c0d915d 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,8 +76,8 @@ pub use execution::{ }; #[cfg(feature = "web3")] pub use ops::{ - derive_recovery_material, 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 4541a4fe29f..7d983973126 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,94 @@ 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; diff --git a/crates/openhuman-core/src/web3/wallet/ops/state.rs b/crates/openhuman-core/src/web3/wallet/ops/state.rs index aa402e7e202..8d8e81e5abd 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): (Vec<_>, Vec<_>) = 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, }, } 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, } diff --git a/crates/openhuman-core/src/web3/wallet/ops_tests.rs b/crates/openhuman-core/src/web3/wallet/ops_tests.rs index 78ea6219ed9..a7dfd288bd9 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,193 @@ 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::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"); + 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.rs b/crates/openhuman-core/src/web3/wallet/policy.rs index 637bd579d61..7069f20e292 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. @@ -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 } @@ -150,6 +150,21 @@ 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, + /// The declared token debits disagree with what the transaction moves + /// (its visible transfers, or its simulation), or the simulation failed. + SimulationMismatch, } /// A refused execute. @@ -165,7 +180,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 +299,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 +362,8 @@ fn new_record( 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..7176b33786e 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() } } @@ -464,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, RECIPIENT, 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, RECIPIENT, 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/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 new file mode 100644 index 00000000000..307a5d6c59a --- /dev/null +++ b/crates/openhuman-core/src/web3/wallet/program/mod.rs @@ -0,0 +1,700 @@ +//! 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), 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 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 +//! 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), 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 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), +//! 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. +//! +//! 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 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. + +use std::collections::BTreeMap; + +use serde::{Deserialize, Serialize}; + +use crate::config::schema::WalletPolicyConfig; + +use super::ledger::{LedgerKind, LedgerRecord}; +use super::policy::{refusal, 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-"; + +pub(super) const DAY_MS: u64 = 24 * 60 * 60 * 1000; +/// SPL Token `TransferChecked`. +const TOKEN_TRANSFER_CHECKED: u8 = 12; +pub(super) 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 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). + 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; + let signatures = reader + .take( + signature_count + .checked_mul(64) + .ok_or("too many signatures")?, + )? + .as_chunks::<64>() + .0 + .to_vec(); + 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, + signatures, + message: bytes[message_start..].to_vec(), + versioned, + num_required_signatures, + account_keys, + recent_blockhash, + instructions, + lookup_table_count, + }) +} + +/// `bytes` with `signature` in every signer slot whose key is `signer`. +/// +/// # Errors +/// +/// When `signer` holds no signer slot. +pub fn attach_signature( + bytes: &[u8], + decoded: &DecodedTransaction, + signer: &[u8; 32], + signature: &[u8; 64], +) -> Result, String> { + let mut signed = bytes.to_vec(); + 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() +} + +// ── 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: 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, + 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, 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. +/// +/// # 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 == 0 + || usize::from(tx.num_required_signatures) != tx.signature_count + { + return Err(structural(format!( + "the transaction needs {} signatures but carries {} slots", + 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}" + ))); + } + 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 + .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); + } + // 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" + ))); + } + _ => {} + } + 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, + signers, + 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 ────────────────────────────────────────────────────────────────── + +/// 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` 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 +/// +/// The refusal, naming the rule and the amounts. +pub fn evaluate_program( + policy: &WalletPolicyConfig, + chain: &str, + account_index: u32, + summary: &ProgramTransactionSummary, + declared: &[MintTotal], + 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"), + )); + } + 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 debits {} mints; a program execute may move at most one", + debits.len() + ))); + } + let Some(total) = debits.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 = total.amount(); + 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(()) +} + +mod ops; +pub(crate) mod schemas; +pub mod simulate; +pub use ops::{ + execute_prepared_program, prepare_program, ExecuteProgramParams, ExecutedProgram, + PrepareProgramParams, PreparedProgram, +}; +#[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 new file mode 100644 index 00000000000..52d8d819924 --- /dev/null +++ b/crates/openhuman-core/src/web3/wallet/program/mod_tests.rs @@ -0,0 +1,677 @@ +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`). +pub(super) const SIGNER: &str = "Hh8QwFUA6MtVu1qAoq12ucvFHNwCcVTV7hpWjeY1Hztb"; +pub(super) const NOW: u64 = 30 * DAY_MS; + +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") +} + +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. +pub(super) const REWARDS_PROGRAM: &str = "REWArDioXgQJ2fZKkfu9LCLjQfRwYWVVfsvcsR5hoXi"; + +pub(super) fn mint() -> String { + TINY_MINT.to_string() +} + +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. +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. +pub(super) 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) { + 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_2022_PROGRAM), + accounts: vec![filled(1), key(mint), filled(2), key(SIGNER)], + data, + } +} + +fn distributor_call() -> Ix { + Ix { + program: key(REWARDS_PROGRAM), + 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], + } +} + +pub(super) fn policy() -> WalletPolicyConfig { + let mut policy = WalletPolicyConfig::default(); + policy.accounts.insert( + "solana_1".into(), + WalletAccountPolicy { + allowed_programs: vec![ + TOKEN_2022_PROGRAM.into(), + ASSOCIATED_TOKEN_PROGRAM.into(), + REWARDS_PROGRAM.to_string(), + ], + 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() +} + +pub(super) 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)]), + 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, + }; + 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_2022_PROGRAM.to_string(), + REWARDS_PROGRAM.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, &summary.totals, &[], 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![REWARDS_PROGRAM.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, + &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 + )), + 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, &summary.totals, &[], NOW).unwrap_err(); + assert_eq!(refused.kind, RefusalKind::ProgramNotAllowed); + assert!( + refused.message.contains(&base58(&filled(42))), + "{}", + refused.message + ); + assert!(refused + .to_string() + .starts_with(crate::web3::wallet::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, + &summary.totals, + &[], + NOW + )), + RefusalKind::PerTransaction + ); + let at_cap = summary_of(&[transfer_checked(&mint(), 1_000)]); + assert_eq!( + evaluate_program(&policy(), "solana", 1, &at_cap, &at_cap.totals, &[], 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, + &summary.totals, + &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, &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, + &small.totals, + &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, + &summary.totals, + &[], + 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, + &summary.totals, + &[], + 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_is_refused() { + let tx = build(filled(4), 1, &[distributor_call()], None); + assert_eq!( + summarize_kind(&tx, 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, &key(SIGNER), &[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), + expected_debits: Vec::new(), + }, + ) + .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")); +} + +pub(super) 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 new file mode 100644 index 00000000000..a365603dbef --- /dev/null +++ b/crates/openhuman-core/src/web3/wallet/program/ops.rs @@ -0,0 +1,475 @@ +//! 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, 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, +}; + +// ── 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, + /// 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, +} + +/// 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 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 + /// apply to these amounts, and the simulation must debit exactly them. + #[serde(alias = "expected_debits")] + pub expected_debits: Vec, +} + +/// `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)?; + 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)?; + 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, + }; + 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. +pub(crate) fn program_record( + prepared: &PreparedProgram, + origin: &ExecutionOrigin, + status: LedgerStatus, + now_ms: u64, +) -> LedgerRecord { + 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(), + [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)?; + // 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() + }) { + 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, + &prepared.declared_debits, + 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 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( + &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()) +} + +/// 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 new file mode 100644 index 00000000000..7a4e4bc4ece --- /dev/null +++ b/crates/openhuman-core/src/web3/wallet/program/schemas.rs @@ -0,0 +1,135 @@ +//! 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, 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 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 { + name: "result", + ty: TypeSchema::Json, + 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 (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."), + ], + 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/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; 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..7730bf9027a --- /dev/null +++ b/crates/openhuman-core/src/web3/wallet/program/simulate_tests.rs @@ -0,0 +1,172 @@ +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()); +} diff --git a/crates/openhuman-core/src/web3/wallet/schemas.rs b/crates/openhuman-core/src/web3/wallet/schemas.rs index c3be53b626d..3833557f533 100644 --- a/crates/openhuman-core/src/web3/wallet/schemas.rs +++ b/crates/openhuman-core/src/web3/wallet/schemas.rs @@ -90,11 +90,14 @@ 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"), ] } pub fn all_wallet_registered_controllers() -> Vec { - vec![ + let mut controllers = vec![ RegisteredController { schema: wallet_schemas("status"), handler: handle_status, @@ -175,7 +178,9 @@ pub fn all_wallet_registered_controllers() -> Vec { schema: wallet_schemas("ledger_list"), handler: handle_ledger_list, }, - ] + ]; + controllers.extend(super::program::schemas::registered()); + controllers } pub fn wallet_schemas(function: &str) -> ControllerSchema { @@ -486,6 +491,9 @@ pub fn wallet_schemas(function: &str) -> ControllerSchema { required: true, }], }, + "account" | "prepare_program" | "execute_prepared_program" => { + super::program::schemas::schema(function) + } _ => ControllerSchema { namespace: "wallet", function: "unknown", diff --git a/crates/openhuman-core/src/web3/wallet/schemas_tests.rs b/crates/openhuman-core/src/web3/wallet/schemas_tests.rs index f3ab812ac63..49d5163a7b7 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,12 @@ 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", "expectedDebits"][..], + ), + ("execute_prepared_program", &["accountIndex", "quoteId"][..]), ] { let schema = wallet_schemas(function); expect_schema_input_order(&schema, inputs); 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), } 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, } } diff --git a/docs/gitbooks/en/features/wallet.md b/docs/gitbooks/en/features/wallet.md index 0375ccaf074..9e0aa904928 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 = [ + "TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb", # Token-2022 (or the classic SPL Token program) + "ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL", # Associated Token Account + "", +] + +[[wallet_policy.accounts.solana_1.mints]] +mint = "" +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 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 - [Approval gate](approval-gate.md)