From ef7fb4bb330c83d3d7dc564e496a9b17de9060fc Mon Sep 17 00:00:00 2001 From: pselle Date: Mon, 2 Nov 2026 14:10:52 -0500 Subject: [PATCH] Sign smart account auth entries with signer plugins A smart account's signature is whatever its `__check_auth` expects, so the CLI can't build it. `stellar keys add --smart-account C... --signer-plugin ` saves a smart account identity; when an auth entry needs that contract's signature, `stellar-signer-` gets the signature payload and invocation as JSON on stdin and returns the credential's signature ScVal. After a smart account signs, the transaction is re-simulated in enforce mode so `__check_auth` is in the footprint and fee. Refs #2762. Co-Authored-By: Claude --- .github/workflows/rpc-tests.yml | 1 + Cargo.lock | 18 ++ Cargo.toml | 1 + FULL_HELP_DOCS.md | 3 + Makefile | 1 + .../tests/fixtures/signer-ed25519/Cargo.toml | 14 + .../tests/fixtures/signer-ed25519/src/main.rs | 40 +++ .../test-wasms/ed25519_account/Cargo.toml | 17 ++ .../test-wasms/ed25519_account/src/lib.rs | 49 ++++ .../soroban-test/tests/it/integration.rs | 1 + .../tests/it/integration/smart_account.rs | 109 ++++++++ .../soroban-test/tests/it/integration/util.rs | 1 + .../src/commands/contract/arg_parsing.rs | 13 +- cmd/soroban-cli/src/commands/keys/add.rs | 74 +++++- .../src/commands/keys/public_key.rs | 8 +- cmd/soroban-cli/src/config/key.rs | 54 +++- cmd/soroban-cli/src/config/sc_address.rs | 3 + cmd/soroban-cli/src/signer/mod.rs | 241 +++++++++++++++--- cmd/soroban-cli/src/signer/plugin.rs | 135 ++++++++++ cmd/soroban-cli/src/tx.rs | 21 +- 20 files changed, 767 insertions(+), 37 deletions(-) create mode 100644 cmd/crates/soroban-test/tests/fixtures/signer-ed25519/Cargo.toml create mode 100644 cmd/crates/soroban-test/tests/fixtures/signer-ed25519/src/main.rs create mode 100644 cmd/crates/soroban-test/tests/fixtures/test-wasms/ed25519_account/Cargo.toml create mode 100644 cmd/crates/soroban-test/tests/fixtures/test-wasms/ed25519_account/src/lib.rs create mode 100644 cmd/crates/soroban-test/tests/it/integration/smart_account.rs create mode 100644 cmd/soroban-cli/src/signer/plugin.rs diff --git a/.github/workflows/rpc-tests.yml b/.github/workflows/rpc-tests.yml index 238c3aafa4..1eaca06ca0 100644 --- a/.github/workflows/rpc-tests.yml +++ b/.github/workflows/rpc-tests.yml @@ -51,6 +51,7 @@ jobs: run: gnome-keyring-daemon --components=secrets --daemonize --unlock <<< 'foobar' - run: cargo build --features additional-libs + - run: cargo build --package stellar-signer-test-ed25519 - run: rustup target add wasm32v1-none - run: make build-test-wasms - run: diff --git a/Cargo.lock b/Cargo.lock index d631aa84f5..2b9477c444 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5854,6 +5854,17 @@ dependencies = [ "tokio", ] +[[package]] +name = "stellar-signer-test-ed25519" +version = "30.0.0" +dependencies = [ + "base64 0.21.7", + "ed25519-dalek", + "hex", + "serde_json", + "stellar-strkey", +] + [[package]] name = "stellar-strkey" version = "1.0.0" @@ -6162,6 +6173,13 @@ dependencies = [ "soroban-sdk", ] +[[package]] +name = "test_ed25519_account" +version = "30.0.0" +dependencies = [ + "soroban-sdk", +] + [[package]] name = "test_empty_constructor" version = "30.0.0" diff --git a/Cargo.toml b/Cargo.toml index 5311e182d3..100d25bd4c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -8,6 +8,7 @@ members = [ "cmd/crates/soroban-test/tests/fixtures/test-wasms/*", "cmd/crates/soroban-test/tests/fixtures/hello", "cmd/crates/soroban-test/tests/fixtures/bye", + "cmd/crates/soroban-test/tests/fixtures/signer-ed25519", ] default-members = [ "cmd/soroban-cli", diff --git a/FULL_HELP_DOCS.md b/FULL_HELP_DOCS.md index 4e9b6d67da..fffec87ed6 100644 --- a/FULL_HELP_DOCS.md +++ b/FULL_HELP_DOCS.md @@ -1321,6 +1321,9 @@ Add a new identity (keypair, ledger, OS specific secure store) - `--ledger` — Derive the address from a connected Ledger hardware wallet at `m/44'/148'/N'`, where `N` defaults to 0 and can be set with `--hd-path`. Persists the derived public key (and `--hd-path`, when provided) so later commands work without the device - `--overwrite` — Overwrite existing identity if it already exists. When combined with --secure-store, also replaces the existing Secure Store entry - `--hd-path ` — When importing a seed phrase, which `hd_path` to derive the key at. Persisted on the identity so later commands derive the same account without re-passing the flag. Not valid with `--public-key` or a raw secret key +- `--smart-account ` — Add a smart account (contract address, C...). Its auth entries are signed by the `stellar-signer-` plugin named with `--signer-plugin` +- `--signer-plugin ` — Name of the signer plugin for `--smart-account`, run as `stellar-signer-` from your PATH +- `--plugin-arg ` — Argument for the signer plugin, as KEY=VALUE. Can be repeated ## `stellar keys public-key` diff --git a/Makefile b/Makefile index 4641ae5dc2..043b03baa0 100644 --- a/Makefile +++ b/Makefile @@ -31,6 +31,7 @@ install: build-fixtures: cargo install --force --locked --path ./cmd/crates/soroban-test/tests/fixtures/hello --root ./target --debug --quiet cargo install --force --locked --path ./cmd/crates/soroban-test/tests/fixtures/bye --root ./target --debug --quiet + cargo install --force --locked --path ./cmd/crates/soroban-test/tests/fixtures/signer-ed25519 --root ./target --debug --quiet # regenerate the example lib in `cmd/crates/soroban-spec-typsecript/fixtures/ts` build-snapshot: typescript-bindings-fixtures diff --git a/cmd/crates/soroban-test/tests/fixtures/signer-ed25519/Cargo.toml b/cmd/crates/soroban-test/tests/fixtures/signer-ed25519/Cargo.toml new file mode 100644 index 0000000000..8bbfb8c244 --- /dev/null +++ b/cmd/crates/soroban-test/tests/fixtures/signer-ed25519/Cargo.toml @@ -0,0 +1,14 @@ +[package] +name = "stellar-signer-test-ed25519" +version = "30.0.0" +edition = "2021" +publish = false + +# Test signer plugin for the `test_ed25519_account` smart account. + +[dependencies] +base64 = { workspace = true } +ed25519-dalek = { workspace = true } +hex = { workspace = true } +serde_json = { workspace = true } +stellar-strkey = { workspace = true } diff --git a/cmd/crates/soroban-test/tests/fixtures/signer-ed25519/src/main.rs b/cmd/crates/soroban-test/tests/fixtures/signer-ed25519/src/main.rs new file mode 100644 index 0000000000..cf5853c515 --- /dev/null +++ b/cmd/crates/soroban-test/tests/fixtures/signer-ed25519/src/main.rs @@ -0,0 +1,40 @@ +//! Signer plugin for the `test_ed25519_account` smart account: signs the +//! request's `payload` with the identity named by `args.key`, and returns the +//! signature as an `ScVal::Bytes`. + +use std::io::Read; +use std::process::Command; + +use base64::Engine as _; +use ed25519_dalek::{Signer as _, SigningKey}; + +const SCV_BYTES: u32 = 13; + +fn main() { + let mut input = String::new(); + std::io::stdin().read_to_string(&mut input).unwrap(); + let request: serde_json::Value = serde_json::from_str(&input).unwrap(); + assert_eq!(request["mode"], "sign_auth"); + + let key = request["args"]["key"] + .as_str() + .expect("args.key is required"); + let stellar = std::env::var("STELLAR_BIN").expect("STELLAR_BIN is set"); + let output = Command::new(stellar) + .args(["keys", "secret", key]) + .output() + .unwrap(); + assert!(output.status.success(), "stellar keys secret {key} failed"); + let secret = String::from_utf8(output.stdout).unwrap(); + let secret = stellar_strkey::ed25519::PrivateKey::from_string(secret.trim()).unwrap(); + + let payload = hex::decode(request["payload"].as_str().unwrap()).unwrap(); + let signature = SigningKey::from_bytes(&secret.0).sign(&payload).to_bytes(); + + // XDR for ScVal::Bytes(signature) + let mut xdr = Vec::with_capacity(72); + xdr.extend_from_slice(&SCV_BYTES.to_be_bytes()); + xdr.extend_from_slice(&u32::try_from(signature.len()).unwrap().to_be_bytes()); + xdr.extend_from_slice(&signature); + println!("{}", base64::engine::general_purpose::STANDARD.encode(xdr)); +} diff --git a/cmd/crates/soroban-test/tests/fixtures/test-wasms/ed25519_account/Cargo.toml b/cmd/crates/soroban-test/tests/fixtures/test-wasms/ed25519_account/Cargo.toml new file mode 100644 index 0000000000..85fb722f2d --- /dev/null +++ b/cmd/crates/soroban-test/tests/fixtures/test-wasms/ed25519_account/Cargo.toml @@ -0,0 +1,17 @@ +[package] +name = "test_ed25519_account" +version = "30.0.0" +authors = ["Stellar Development Foundation "] +license = "Apache-2.0" +edition = "2021" +publish = false + +[lib] +crate-type = ["cdylib"] +doctest = false + +[dependencies] +soroban-sdk = { workspace = true } + +[dev-dependencies] +soroban-sdk = { workspace = true, features = ["testutils"]} diff --git a/cmd/crates/soroban-test/tests/fixtures/test-wasms/ed25519_account/src/lib.rs b/cmd/crates/soroban-test/tests/fixtures/test-wasms/ed25519_account/src/lib.rs new file mode 100644 index 0000000000..09bb334f20 --- /dev/null +++ b/cmd/crates/soroban-test/tests/fixtures/test-wasms/ed25519_account/src/lib.rs @@ -0,0 +1,49 @@ +#![no_std] +//! A smart account with one ed25519 signer, for testing signer plugins. +use soroban_sdk::{ + auth::{Context, CustomAccountInterface}, + contract, contracterror, contractimpl, + crypto::Hash, + symbol_short, BytesN, Env, Symbol, Vec, +}; + +const SIGNER: Symbol = symbol_short!("signer"); + +#[contract] +pub struct Contract; + +#[contracterror] +#[derive(Copy, Clone, Eq, PartialEq, Debug)] +pub enum Error { + NoSigner = 1, +} + +#[contractimpl] +impl Contract { + pub fn __constructor(env: Env, signer: BytesN<32>) { + env.storage().instance().set(&SIGNER, &signer); + } +} + +#[contractimpl] +impl CustomAccountInterface for Contract { + type Error = Error; + type Signature = BytesN<64>; + + #[allow(non_snake_case)] + fn __check_auth( + env: Env, + signature_payload: Hash<32>, + signature: BytesN<64>, + _auth_contexts: Vec, + ) -> Result<(), Error> { + let signer: BytesN<32> = env + .storage() + .instance() + .get(&SIGNER) + .ok_or(Error::NoSigner)?; + env.crypto() + .ed25519_verify(&signer, &signature_payload.into(), &signature); + Ok(()) + } +} diff --git a/cmd/crates/soroban-test/tests/it/integration.rs b/cmd/crates/soroban-test/tests/it/integration.rs index 033a9b704d..6ec59fa726 100644 --- a/cmd/crates/soroban-test/tests/it/integration.rs +++ b/cmd/crates/soroban-test/tests/it/integration.rs @@ -14,6 +14,7 @@ mod ledger; mod network; mod pull; mod secure_store; +mod smart_account; mod snapshot; mod token; mod tx; diff --git a/cmd/crates/soroban-test/tests/it/integration/smart_account.rs b/cmd/crates/soroban-test/tests/it/integration/smart_account.rs new file mode 100644 index 0000000000..4f634ab1f5 --- /dev/null +++ b/cmd/crates/soroban-test/tests/it/integration/smart_account.rs @@ -0,0 +1,109 @@ +use std::ffi::OsString; + +use soroban_test::{AssertExt, TestEnv}; + +use super::util::{extend_contract, new_account, AUTH, ED25519_ACCOUNT}; + +/// PATH with the directory `stellar` was built into, where `cargo build +/// --package stellar-signer-test-ed25519` puts the test signer plugin. +fn path_with_test_plugin() -> OsString { + let stellar = assert_cmd::cargo::cargo_bin("stellar"); + let dir = stellar.parent().unwrap().to_path_buf(); + let paths = std::env::var_os("PATH").unwrap_or_default(); + std::env::join_paths(std::iter::once(dir).chain(std::env::split_paths(&paths))).unwrap() +} + +/// Deploy a `test_ed25519_account` signed for by identity `signer`, and save +/// it as identity `name` using `plugin`. +async fn add_smart_account(sandbox: &TestEnv, name: &str, signer: &str, plugin: &str) -> String { + let signer_pk = new_account(sandbox, signer); + let signer_pk = stellar_strkey::ed25519::PublicKey::from_string(&signer_pk).unwrap(); + let account = sandbox + .new_assert_cmd("contract") + .arg("deploy") + .arg("--source=test") + .arg("--wasm") + .arg(ED25519_ACCOUNT.path()) + .arg("--") + .arg("--signer") + .arg(hex::encode(signer_pk.0)) + .assert() + .success() + .stdout_as_str(); + extend_contract(sandbox, &account).await; + sandbox + .new_assert_cmd("keys") + .args(["add", name, "--smart-account", &account]) + .args(["--signer-plugin", plugin, "--plugin-arg"]) + .arg(format!("key={signer}")) + .assert() + .success(); + account +} + +async fn deploy_auth(sandbox: &TestEnv) -> String { + let id = sandbox + .new_assert_cmd("contract") + .arg("deploy") + .arg("--source=test") + .arg("--wasm") + .arg(AUTH.path()) + .arg("--") + .arg("--addr=test") + .assert() + .success() + .stdout_as_str(); + extend_contract(sandbox, &id).await; + id +} + +#[tokio::test] +async fn smart_account_signs_with_plugin() { + let sandbox = &TestEnv::new(); + let account = add_smart_account(sandbox, "sa", "sa-signer", "test-ed25519").await; + sandbox + .new_assert_cmd("keys") + .args(["address", "sa"]) + .assert() + .success() + .stdout(format!("{account}\n")); + + let id = deploy_auth(sandbox).await; + sandbox + .new_assert_cmd("contract") + .env("PATH", path_with_test_plugin()) + .arg("invoke") + .arg("--source=test") + .arg("--id") + .arg(&id) + .arg("--") + .arg("do-auth") + .arg("--addr=sa") + .arg("--val=hello") + .assert() + .success() + .stdout("\"hello\"\n"); +} + +#[tokio::test] +async fn smart_account_plugin_not_installed() { + let sandbox = &TestEnv::new(); + add_smart_account(sandbox, "sa", "sa-signer", "not-installed").await; + + let id = deploy_auth(sandbox).await; + sandbox + .new_assert_cmd("contract") + .arg("invoke") + .arg("--source=test") + .arg("--id") + .arg(&id) + .arg("--") + .arg("do-auth") + .arg("--addr=sa") + .arg("--val=hello") + .assert() + .failure() + .stderr(predicates::str::contains( + "signer plugin `stellar-signer-not-installed` not found on PATH", + )); +} diff --git a/cmd/crates/soroban-test/tests/it/integration/util.rs b/cmd/crates/soroban-test/tests/it/integration/util.rs index f2c811c6fd..c43ad8baeb 100644 --- a/cmd/crates/soroban-test/tests/it/integration/util.rs +++ b/cmd/crates/soroban-test/tests/it/integration/util.rs @@ -10,6 +10,7 @@ pub const HELLO_WORLD: &Wasm = &Wasm::Custom("test-wasms", "test_hello_world"); pub const CONSTRUCTOR: &Wasm = &Wasm::Custom("test-wasms", "test_constructor"); pub const CUSTOM_TYPES: &Wasm = &Wasm::Custom("test-wasms", "test_custom_types"); pub const CUSTOM_ACCOUNT: &Wasm = &Wasm::Custom("test-wasms", "test_custom_account"); +pub const ED25519_ACCOUNT: &Wasm = &Wasm::Custom("test-wasms", "test_ed25519_account"); pub const SWAP: &Wasm = &Wasm::Custom("test-wasms", "test_swap"); pub async fn invoke(sandbox: &TestEnv, id: &str, func: &str, data: &str) -> String { diff --git a/cmd/soroban-cli/src/commands/contract/arg_parsing.rs b/cmd/soroban-cli/src/commands/contract/arg_parsing.rs index 8acbce9d7e..c0d11df8db 100644 --- a/cmd/soroban-cli/src/commands/contract/arg_parsing.rs +++ b/cmd/soroban-cli/src/commands/contract/arg_parsing.rs @@ -3,7 +3,7 @@ use crate::commands::contract::deploy::wasm::CONSTRUCTOR_FUNCTION_NAME; use crate::commands::txn_result::TxnResult; use crate::config::{self, sc_address, UnresolvedScAddress}; use crate::print::Print; -use crate::signer::{self, Signer}; +use crate::signer::{self, plugin::PluginSigner, Signer, SignerKind}; use crate::xdr::{ self, Hash, InvokeContractArgs, ScSpecEntry, ScSpecFunctionV0, ScSpecTypeDef, ScVal, ScVec, }; @@ -584,6 +584,17 @@ fn resolve_address( } fn resolve_signer(addr_or_alias: &str, config: &config::Args) -> Option { + if let Ok(config::key::Key::SmartAccount(account)) = config.locator.read_identity(addr_or_alias) + { + return Some(Signer { + kind: SignerKind::Plugin(PluginSigner { + address: account.address.0, + plugin: account.signer_plugin, + args: account.plugin_args, + }), + print: Print::new(false), + }); + } let account: config::UnresolvedMuxedAccount = addr_or_alias.parse().ok()?; // A raw public key is matched to an identity at `--hd-path`, so the signer // is built at that same path; an alias or secret honors it the same way. diff --git a/cmd/soroban-cli/src/commands/keys/add.rs b/cmd/soroban-cli/src/commands/keys/add.rs index e31139458a..9760889ca3 100644 --- a/cmd/soroban-cli/src/commands/keys/add.rs +++ b/cmd/soroban-cli/src/commands/keys/add.rs @@ -92,6 +92,31 @@ pub struct Cmd { /// secret key. #[arg(long)] pub hd_path: Option, + + /// Add a smart account (contract address, C...). Its auth entries are + /// signed by the `stellar-signer-` plugin named with + /// `--signer-plugin`. + #[arg( + long, + requires = "signer_plugin", + conflicts_with_all = ["public_key", "ledger", "seed_phrase", "secret_key", "secure_store", "hd_path"] + )] + pub smart_account: Option, + + /// Name of the signer plugin for `--smart-account`, run as + /// `stellar-signer-` from your PATH + #[arg(long, requires = "smart_account", value_name = "NAME")] + pub signer_plugin: Option, + + /// Argument for the signer plugin, as KEY=VALUE. Can be repeated. + #[arg(long, requires = "signer_plugin", value_name = "KEY=VALUE", value_parser = parse_plugin_arg)] + pub plugin_arg: Vec<(String, String)>, +} + +fn parse_plugin_arg(s: &str) -> Result<(String, String), String> { + s.split_once('=') + .map(|(k, v)| (k.to_string(), v.to_string())) + .ok_or_else(|| format!("expected KEY=VALUE, got `{s}`")) } impl Cmd { @@ -106,7 +131,15 @@ impl Cmd { print.exclaimln(format!("Overwriting identity '{}'", self.name)); } - let key = if let Some(key) = self.public_key.as_ref() { + let key = if let (Some(address), Some(signer_plugin)) = + (self.smart_account, self.signer_plugin.as_ref()) + { + key::Key::SmartAccount(key::SmartAccount { + address, + signer_plugin: signer_plugin.clone(), + plugin_args: self.plugin_arg.iter().cloned().collect(), + }) + } else if let Some(key) = self.public_key.as_ref() { key::Key::parse_public_only(key)? } else if self.ledger { self.derive_ledger_secret().await?.into() @@ -217,6 +250,7 @@ mod tests { use crate::config::key::{self as key_mod, Key}; const PUBLIC_KEY: &str = "GAKSH6AD2IPJQELTHIOWDAPYX74YELUOWJLI2L4RIPIPZH6YQIFNUSDC"; + const CONTRACT: &str = "CADQOBYHA4DQOBYHA4DQOBYHA4DQOBYHA4DQOBYHA4DQOBYHA4DQP5KR"; const MUXED_ACCOUNT: &str = "MA3D5KRYM6CB7OWQ6TWYRR3Z4T7GNZLKERYNZGGA5SOAOPIFY6YQGAAAAAAAAAPCICBKU"; const SECRET_KEY: &str = "SBF5HLRREHMS36XZNTUSKZ6FTXDZGNXOHF4EXKUL5UCWZLPBX3NGJ4BH"; @@ -240,6 +274,9 @@ mod tests { ledger: false, overwrite: false, hd_path: None, + smart_account: None, + signer_plugin: None, + plugin_arg: vec![], }; (temp_dir, locator, cmd) } @@ -377,6 +414,41 @@ mod tests { assert!(matches!(stored, Key::PublicKey(_))); } + #[tokio::test] + async fn smart_account_flags_store_smart_account() { + use clap::Parser; + + let temp_dir = tempfile::tempdir().unwrap(); + let mut cmd = Cmd::try_parse_from([ + "add", + "sa", + "--smart-account", + CONTRACT, + "--signer-plugin", + "oz", + "--plugin-arg", + "rule-id=1", + ]) + .unwrap(); + cmd.config_locator.config_dir = Some(temp_dir.path().to_path_buf()); + cmd.run(&global_args()).await.unwrap(); + let Key::SmartAccount(stored) = cmd.config_locator.read_identity("sa").unwrap() else { + panic!("expected a smart account"); + }; + assert_eq!(stored.address.to_string(), CONTRACT); + assert_eq!(stored.signer_plugin, "oz"); + assert_eq!(stored.plugin_args["rule-id"], "1"); + } + + #[test] + fn test_clap_requires_signer_plugin_with_smart_account() { + use clap::Parser; + + let err = Cmd::try_parse_from(["add", "sa", "--smart-account", CONTRACT]) + .expect_err("--smart-account needs --signer-plugin"); + assert_eq!(err.kind(), clap::error::ErrorKind::MissingRequiredArgument); + } + #[tokio::test] async fn public_key_flag_accepts_muxed_account() { let (_tmp, locator, mut cmd) = set_up_test(); diff --git a/cmd/soroban-cli/src/commands/keys/public_key.rs b/cmd/soroban-cli/src/commands/keys/public_key.rs index a28ea1dac8..a47497da36 100644 --- a/cmd/soroban-cli/src/commands/keys/public_key.rs +++ b/cmd/soroban-cli/src/commands/keys/public_key.rs @@ -1,6 +1,6 @@ use crate::{ commands::config::{address, locator}, - config::UnresolvedMuxedAccount, + config::{key::Key, UnresolvedMuxedAccount}, signer::ledger, }; @@ -37,6 +37,12 @@ pub struct Cmd { impl Cmd { pub async fn run(&self) -> Result<(), Error> { + if let Some(UnresolvedMuxedAccount::AliasOrSecret(name)) = &self.name { + if let Ok(Key::SmartAccount(account)) = self.locator.read_identity(name) { + println!("{}", account.address); + return Ok(()); + } + } println!("{}", self.public_key().await?); Ok(()) } diff --git a/cmd/soroban-cli/src/config/key.rs b/cmd/soroban-cli/src/config/key.rs index 5f281f3ed5..736f7779cd 100644 --- a/cmd/soroban-cli/src/config/key.rs +++ b/cmd/soroban-cli/src/config/key.rs @@ -1,4 +1,4 @@ -use std::{fmt::Display, str::FromStr}; +use std::{collections::BTreeMap, fmt::Display, str::FromStr}; use serde::{Deserialize, Serialize}; @@ -17,6 +17,8 @@ pub enum Error { Parse, #[error("expected a public key (G...) or muxed account (M...)")] PublicKeyExpected, + #[error("smart account {0} is a contract, not an account; it can't be a transaction source or sign one")] + SmartAccountNotAnAccount(stellar_strkey::Contract), } #[derive(Debug, Serialize, Deserialize, PartialEq, Eq)] @@ -25,6 +27,8 @@ pub enum Key { PublicKey(Public), #[serde(rename = "muxed_account")] MuxedAccount(MuxedAccount), + #[serde(rename = "smart_account")] + SmartAccount(SmartAccount), #[serde(untagged)] Secret(Secret), } @@ -43,6 +47,9 @@ impl Key { id: *id, })) } + Key::SmartAccount(account) => { + return Err(Error::SmartAccountNotAnAccount(account.address.0)); + } }; Ok(xdr::MuxedAccount::Ed25519(xdr::Uint256(bytes))) } @@ -60,7 +67,7 @@ impl Key { pub fn parse_public_only(s: &str) -> Result { match s.parse()? { key @ (Key::PublicKey(_) | Key::MuxedAccount(_)) => Ok(key), - Key::Secret(_) => Err(Error::PublicKeyExpected), + Key::Secret(_) | Key::SmartAccount(_) => Err(Error::PublicKeyExpected), } } } @@ -82,6 +89,36 @@ impl FromStr for Key { } } +/// A contract account whose auth entries are signed by the external +/// `stellar-signer-` binary. +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] +pub struct SmartAccount { + pub address: Contract, + pub signer_plugin: String, + /// Passed through to the plugin as `args`. + #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] + pub plugin_args: BTreeMap, +} + +#[derive( + Debug, Clone, Copy, PartialEq, Eq, serde_with::SerializeDisplay, serde_with::DeserializeFromStr, +)] +pub struct Contract(pub stellar_strkey::Contract); + +impl FromStr for Contract { + type Err = stellar_strkey::DecodeError; + + fn from_str(s: &str) -> Result { + Ok(Contract(stellar_strkey::Contract::from_string(s)?)) + } +} + +impl Display for Contract { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "{}", self.0) + } +} + impl From for Key { fn from(value: stellar_strkey::ed25519::PublicKey) -> Self { Key::PublicKey(Public(value)) @@ -186,6 +223,19 @@ mod test { round_trip(&key); } #[test] + fn smart_account() { + let key = Key::SmartAccount(SmartAccount { + address: Contract(stellar_strkey::Contract([7; 32])), + signer_plugin: "oz".to_string(), + plugin_args: BTreeMap::from([("rule-id".to_string(), "1".to_string())]), + }); + round_trip(&key); + assert!(matches!( + key.muxed_account(None), + Err(Error::SmartAccountNotAnAccount(_)) + )); + } + #[test] fn secret_seed_phrase() { let seed_phrase = "singer swing mango apple singer swing mango apple singer swing mango apple singer swing mango apple".to_string(); let secret = Secret::SeedPhrase { diff --git a/cmd/soroban-cli/src/config/sc_address.rs b/cmd/soroban-cli/src/config/sc_address.rs index dbf69c400d..f41671af88 100644 --- a/cmd/soroban-cli/src/config/sc_address.rs +++ b/cmd/soroban-cli/src/config/sc_address.rs @@ -151,6 +151,9 @@ impl UnresolvedScAddress { // downgrading to its base `G…` account: collapsing it would target a // different recipient than the one named. Contexts that can't accept // a muxed address reject it up front (see `is_muxed`). + (_, Ok(key::Key::SmartAccount(account))) => Ok(xdr::ScAddress::Contract( + stellar_xdr::ContractId(xdr::Hash(account.address.0 .0)), + )), (_, Ok(key)) => Ok(match key.muxed_account(hd_path)? { xdr::MuxedAccount::Ed25519(ed25519) => xdr::ScAddress::Account(xdr::AccountId( xdr::PublicKey::PublicKeyTypeEd25519(ed25519), diff --git a/cmd/soroban-cli/src/signer/mod.rs b/cmd/soroban-cli/src/signer/mod.rs index c63c50666a..8d1b271599 100644 --- a/cmd/soroban-cli/src/signer/mod.rs +++ b/cmd/soroban-cli/src/signer/mod.rs @@ -7,8 +7,8 @@ use crate::{ HashIdPreimageSorobanAuthorization, HashIdPreimageSorobanAuthorizationWithAddress, Limits, MuxedAccount, Operation, OperationBody, PublicKey, ScAddress, ScMap, ScSymbol, ScVal, Signature, SignatureHint, SorobanAddressCredentials, SorobanAuthorizationEntry, - SorobanCredentials, Transaction, TransactionEnvelope, TransactionV1Envelope, Uint256, VecM, - WriteXdr, + SorobanAuthorizedInvocation, SorobanCredentials, Transaction, TransactionEnvelope, + TransactionV1Envelope, Uint256, VecM, WriteXdr, }, }; use ed25519_dalek::{ed25519::signature::Signer as _, Signature as Ed25519Signature}; @@ -19,6 +19,7 @@ use crate::{config::network::Network, print::Print, utils::transaction_hash}; use std::io::{self, BufRead, IsTerminal}; pub mod ledger; +pub mod plugin; pub mod validation; #[cfg(feature = "additional-libs")] @@ -62,6 +63,12 @@ pub enum Error { Decode(#[from] stellar_strkey::DecodeError), #[error(transparent)] Validation(#[from] validation::Error), + #[error(transparent)] + Plugin(#[from] plugin::Error), + #[error("Smart account {address} has no signer plugin. Add one with `stellar keys add --smart-account {address} --signer-plugin ` and pass that name as the address")] + MissingPluginForContract { address: String }, + #[error("Signer plugins only sign authorization entries, not transactions")] + PluginCannotSignTransaction, } /// Sign all SorobanAuthorizationEntry's in the transaction with the given signers. Returns a new @@ -135,14 +142,26 @@ pub async fn sign_soroban_authorizations( ScAddress::LiquidityPool(_) => todo!("liquidity pool not supported"), ScAddress::Account(AccountId(PublicKey::PublicKeyTypeEd25519(Uint256(ref a)))) => a, ScAddress::Contract(stellar_xdr::ContractId(Hash(c))) => { - // This address is for a contract. This means we're using a custom - // smart-contract account. Currently the CLI doesn't support that yet. - return Err(Error::MissingSignerForAddress { - address: format!( - "{}", - stellar_strkey::Strkey::Contract(stellar_strkey::Contract(*c)) - ), + // A smart account: only a plugin that knows its `__check_auth` + // can sign for it. + let plugin = signers.iter().find_map(|s| match &s.kind { + SignerKind::Plugin(p) if p.address.0 == *c => Some(p), + _ => None, }); + let Some(plugin) = plugin else { + return Err(Error::MissingPluginForContract { + address: format!("{}", stellar_strkey::Contract(*c)), + }); + }; + signed_auths.push(sign_soroban_authorization_entry_with_plugin( + raw_auth, + plugin, + signature_expiration_ledger, + network_passphrase, + &network_id, + )?); + auths_modified = true; + continue; } ScAddress::MuxedContract(_) => { return Err(Error::MissingSignerForAddress { @@ -161,6 +180,9 @@ pub async fn sign_soroban_authorizations( let mut signer: Option<&Signer> = None; for s in signers { + if matches!(s.kind, SignerKind::Plugin(_)) { + continue; + } if auth_address_bytes == &s.get_public_key()?.0 { signer = Some(s); break; @@ -250,27 +272,16 @@ fn confirm_non_strict_authorization(auth: &SorobanAuthorizationEntry) -> Result< } } -async fn sign_soroban_authorization_entry( - raw: &SorobanAuthorizationEntry, - signer: &Signer, +/// The hash an `Address` (V1) or `AddressV2` credential signs. V2 binds the +/// signer's address into the payload (CAP-0071-02) via the +/// `SorobanAuthorizationWithAddress` preimage; V1 omits it. +fn auth_payload( + credentials: &SorobanAddressCredentials, + is_v2: bool, + invocation: SorobanAuthorizedInvocation, signature_expiration_ledger: u32, network_id: &Hash, -) -> Result { - let mut auth = raw.clone(); - let invocation = auth.root_invocation.clone(); - // `Address` (V1) and `AddressV2` share the same credential struct; only the - // signature payload differs. The RPC returns V1 by default, but we sign - // whichever variant the entry carries and preserve it on the way out. - let (credentials, is_v2) = match &mut auth.credentials { - SorobanCredentials::Address(credentials) => (credentials, false), - SorobanCredentials::AddressV2(credentials) => (credentials, true), - // SourceAccount does not need special signing - // AddressWithDelegates is not supported yet, and a warning is emitted earlier - _ => return Ok(auth), - }; - - // V2 binds the signer's address into the payload (CAP-0071-02) via the - // `SorobanAuthorizationWithAddress` preimage; V1 omits it. +) -> Result<[u8; 32], Error> { let preimage = if is_v2 { HashIdPreimage::SorobanAuthorizationWithAddress( HashIdPreimageSorobanAuthorizationWithAddress { @@ -290,10 +301,69 @@ async fn sign_soroban_authorization_entry( }) } .to_xdr(Limits::depth(XDR_DEPTH_LIMIT))?; + Ok(Sha256::digest(preimage).into()) +} + +fn sign_soroban_authorization_entry_with_plugin( + raw: &SorobanAuthorizationEntry, + plugin: &plugin::PluginSigner, + signature_expiration_ledger: u32, + network_passphrase: &str, + network_id: &Hash, +) -> Result { + let mut auth = raw.clone(); + let invocation = auth.root_invocation.clone(); + let (credentials, is_v2) = match &mut auth.credentials { + SorobanCredentials::Address(credentials) => (credentials, false), + SorobanCredentials::AddressV2(credentials) => (credentials, true), + _ => return Ok(auth), + }; + let payload = auth_payload( + credentials, + is_v2, + invocation.clone(), + signature_expiration_ledger, + network_id, + )?; + credentials.signature = plugin.sign_auth( + network_passphrase, + credentials.nonce, + signature_expiration_ledger, + is_v2, + payload, + &invocation, + )?; + credentials.signature_expiration_ledger = signature_expiration_ledger; + Ok(auth) +} - let payload = Sha256::digest(preimage); - let p: [u8; 32] = payload.as_slice().try_into()?; - let signature = signer.sign_payload(p).await?; +async fn sign_soroban_authorization_entry( + raw: &SorobanAuthorizationEntry, + signer: &Signer, + signature_expiration_ledger: u32, + network_id: &Hash, +) -> Result { + let mut auth = raw.clone(); + let invocation = auth.root_invocation.clone(); + // `Address` (V1) and `AddressV2` share the same credential struct; only the + // signature payload differs. The RPC returns V1 by default, but we sign + // whichever variant the entry carries and preserve it on the way out. + let (credentials, is_v2) = match &mut auth.credentials { + SorobanCredentials::Address(credentials) => (credentials, false), + SorobanCredentials::AddressV2(credentials) => (credentials, true), + // SourceAccount does not need special signing + // AddressWithDelegates is not supported yet, and a warning is emitted earlier + _ => return Ok(auth), + }; + + let payload = auth_payload( + credentials, + is_v2, + invocation, + signature_expiration_ledger, + network_id, + )?; + let signature = signer.sign_payload(payload).await?; let public_key_vec = signer.get_public_key()?.0.to_vec(); let map = ScMap::sorted_from(vec![ @@ -331,6 +401,7 @@ pub enum SignerKind { Ledger(LedgerEntry), Lab, SecureStore(SecureStoreEntry), + Plugin(plugin::PluginSigner), } // It is advised to use the sign_with module, which handles creating a Signer with the appropriate SignerKind @@ -393,6 +464,7 @@ impl Signer { .expect("Ledger signers reachable here are built from Secret::Ledger and always carry a cached public key")), SignerKind::Lab => Err(Error::ReturningSignatureFromLab), SignerKind::SecureStore(secure_store_entry) => secure_store_entry.get_public_key(), + SignerKind::Plugin(_) => Err(Error::PluginCannotSignTransaction), } } @@ -402,6 +474,7 @@ impl Signer { SignerKind::Ledger(ledger) => Ok(ledger.sign_payload(payload).await?), SignerKind::Lab => Err(Error::ReturningSignatureFromLab), SignerKind::SecureStore(secure_store_entry) => secure_store_entry.sign_payload(payload), + SignerKind::Plugin(_) => Err(Error::PluginCannotSignTransaction), } } @@ -416,6 +489,7 @@ impl Signer { SignerKind::Lab => Lab::sign_tx_env(tx_env, network, &self.print), SignerKind::Ledger(ledger) => ledger.sign_tx_hash(tx_hash).await.map_err(Error::from), SignerKind::SecureStore(entry) => entry.sign_tx_hash(tx_hash), + SignerKind::Plugin(_) => Err(Error::PluginCannotSignTransaction), } } } @@ -929,4 +1003,109 @@ mod tests { "V2 must bind the address, producing a different signature than V1", ); } + + // ---- Smart accounts (contract addresses) ---- + + fn contract_address(bytes: [u8; 32]) -> ScAddress { + ScAddress::Contract(stellar_xdr::ContractId(Hash(bytes))) + } + + fn plugin_signer(contract: [u8; 32], plugin: &str) -> Signer { + Signer { + kind: SignerKind::Plugin(plugin::PluginSigner { + address: stellar_strkey::Contract(contract), + plugin: plugin.to_string(), + args: std::collections::BTreeMap::new(), + }), + print: Print::new(true), + } + } + + #[tokio::test] + async fn test_contract_address_without_plugin_errors() { + let source = MuxedAccount::Ed25519(Uint256([9u8; 32])); + let contract = [42u8; 32]; + let entry = address_auth(contract_address([7u8; 32]), invocation(contract, "hello")); + let host_fn = HostFunction::InvokeContract(invoke_args(contract, "hello")); + let tx = build_tx(source, host_fn, vec![entry]); + + // A plugin for a different smart account doesn't count. + let result = sign_soroban_authorizations( + &tx, + &[local_signer([1u8; 32]), plugin_signer([8u8; 32], "unused")], + EXPIRATION_LEDGER, + NETWORK, + false, + &Print::new(true), + ) + .await; + assert!(matches!( + result, + Err(Error::MissingPluginForContract { .. }) + )); + } + + #[tokio::test] + async fn test_contract_address_runs_its_plugin() { + let source = MuxedAccount::Ed25519(Uint256([9u8; 32])); + let contract = [42u8; 32]; + let account = [7u8; 32]; + let entry = address_auth(contract_address(account), invocation(contract, "hello")); + let host_fn = HostFunction::InvokeContract(invoke_args(contract, "hello")); + let tx = build_tx(source, host_fn, vec![entry]); + + let result = sign_soroban_authorizations( + &tx, + &[plugin_signer(account, "definitely-not-installed")], + EXPIRATION_LEDGER, + NETWORK, + false, + &Print::new(true), + ) + .await; + assert!(matches!( + result, + Err(Error::Plugin(plugin::Error::NotFound { bin })) + if bin == "stellar-signer-definitely-not-installed" + )); + } + + #[tokio::test] + async fn test_plugin_signer_does_not_match_g_address() { + let signer = local_signer([1u8; 32]); + let signer_pk = signer_pubkey(&signer); + let source = MuxedAccount::Ed25519(Uint256([9u8; 32])); + let contract = [42u8; 32]; + let entry = address_auth(ed25519_address(signer_pk), invocation(contract, "hello")); + let host_fn = HostFunction::InvokeContract(invoke_args(contract, "hello")); + let tx = build_tx(source, host_fn, vec![entry]); + + // A plugin signer earlier in the list is skipped, not an error. + let result = sign_soroban_authorizations( + &tx, + &[plugin_signer([7u8; 32], "unused"), signer], + EXPIRATION_LEDGER, + NETWORK, + false, + &Print::new(true), + ) + .await + .unwrap(); + assert!(result.is_some()); + } + + #[test] + fn test_auth_payload_v1_and_v2_differ() { + let network_id = Hash(Sha256::digest(NETWORK.as_bytes()).into()); + let creds = SorobanAddressCredentials { + address: contract_address([7u8; 32]), + nonce: 3, + signature_expiration_ledger: 0, + signature: ScVal::Void, + }; + let inv = invocation([42u8; 32], "hello"); + let v1 = auth_payload(&creds, false, inv.clone(), EXPIRATION_LEDGER, &network_id).unwrap(); + let v2 = auth_payload(&creds, true, inv, EXPIRATION_LEDGER, &network_id).unwrap(); + assert_ne!(v1, v2); + } } diff --git a/cmd/soroban-cli/src/signer/plugin.rs b/cmd/soroban-cli/src/signer/plugin.rs new file mode 100644 index 0000000000..39e3098373 --- /dev/null +++ b/cmd/soroban-cli/src/signer/plugin.rs @@ -0,0 +1,135 @@ +//! Signs auth entries for smart accounts (contract addresses) by running an +//! external `stellar-signer-` binary, since only the account's own +//! `__check_auth` knows what its signature looks like. +//! +//! The plugin reads one JSON [`SignAuthRequest`] on stdin and writes the +//! credential's `signature` as a base64 XDR `ScVal` on stdout. Its stderr is +//! the user's terminal, so it can prompt. `STELLAR_BIN` names the running +//! `stellar` binary, so the plugin can call e.g. `$STELLAR_BIN keys secret`. + +use std::{ + collections::BTreeMap, + io::Write, + path::PathBuf, + process::{Command, Stdio}, +}; + +use serde::Serialize; + +use crate::{ + utils::XDR_DEPTH_LIMIT, + xdr::{self, Limits, ReadXdr, ScVal, SorobanAuthorizedInvocation, WriteXdr}, +}; + +#[derive(thiserror::Error, Debug)] +pub enum Error { + #[error("signer plugin `{bin}` not found on PATH")] + NotFound { bin: String }, + #[error("failed to run signer plugin `{bin}`: {source}")] + Spawn { bin: String, source: std::io::Error }, + #[error("signer plugin `{bin}` failed ({status})")] + Failed { + bin: String, + status: std::process::ExitStatus, + }, + #[error("signer plugin `{bin}` returned an invalid signature, expected a base64 XDR ScVal: {source}")] + InvalidOutput { bin: String, source: xdr::Error }, + #[error(transparent)] + Xdr(#[from] xdr::Error), + #[error(transparent)] + Json(#[from] serde_json::Error), +} + +pub struct PluginSigner { + pub address: stellar_strkey::Contract, + pub plugin: String, + pub args: BTreeMap, +} + +/// What a plugin is asked to sign. Mirrors what `__check_auth` receives: +/// `payload` is its `signature_payload`, and `root_invocation` its auth +/// context. +#[derive(Serialize, Debug)] +pub struct SignAuthRequest<'a> { + pub mode: &'static str, + pub network_passphrase: &'a str, + pub address: String, + pub nonce: i64, + pub signature_expiration_ledger: u32, + /// `address` for an `Address` credential, `address_v2` for `AddressV2` + pub credential_kind: &'static str, + /// Hex sha256 of the `HashIdPreimage` for the credential kind + pub payload: String, + /// Base64 XDR `SorobanAuthorizedInvocation` + pub root_invocation: String, + pub args: &'a BTreeMap, +} + +impl PluginSigner { + pub fn bin_name(&self) -> String { + format!("stellar-signer-{}", self.plugin) + } + + #[allow(clippy::too_many_arguments)] + pub fn sign_auth( + &self, + network_passphrase: &str, + nonce: i64, + signature_expiration_ledger: u32, + is_v2: bool, + payload: [u8; 32], + invocation: &SorobanAuthorizedInvocation, + ) -> Result { + let request = SignAuthRequest { + mode: "sign_auth", + network_passphrase, + address: format!("{}", self.address), + nonce, + signature_expiration_ledger, + credential_kind: if is_v2 { "address_v2" } else { "address" }, + payload: hex::encode(payload), + root_invocation: invocation.to_xdr_base64(Limits::depth(XDR_DEPTH_LIMIT))?, + args: &self.args, + }; + let stdout = self.run(&serde_json::to_vec(&request)?)?; + ScVal::from_xdr_base64(stdout.trim(), Limits::depth(XDR_DEPTH_LIMIT)).map_err(|source| { + Error::InvalidOutput { + bin: self.bin_name(), + source, + } + }) + } + + fn run(&self, input: &[u8]) -> Result { + let bin = self.bin_name(); + let path: PathBuf = which::which(&bin).map_err(|_| Error::NotFound { bin: bin.clone() })?; + let spawn_err = |source| Error::Spawn { + bin: bin.clone(), + source, + }; + let mut cmd = Command::new(path); + if let Ok(exe) = std::env::current_exe() { + cmd.env("STELLAR_BIN", exe); + } + let mut child = cmd + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::inherit()) + .spawn() + .map_err(spawn_err)?; + child + .stdin + .take() + .expect("stdin is piped") + .write_all(input) + .map_err(spawn_err)?; + let output = child.wait_with_output().map_err(spawn_err)?; + if !output.status.success() { + return Err(Error::Failed { + bin, + status: output.status, + }); + } + Ok(String::from_utf8_lossy(&output.stdout).into_owned()) + } +} diff --git a/cmd/soroban-cli/src/tx.rs b/cmd/soroban-cli/src/tx.rs index 4269616c20..a79b02f27e 100644 --- a/cmd/soroban-cli/src/tx.rs +++ b/cmd/soroban-cli/src/tx.rs @@ -62,7 +62,7 @@ where auth_mode, ) .await?; - let assembled = resources.apply_to_assembled_txn(txn); + let mut assembled = resources.apply_to_assembled_txn(txn); let mut txn = Box::new(assembled.transaction().clone()); let sim_res = assembled.sim_response(); @@ -77,6 +77,25 @@ where .await? { *txn = tx; + // Recording-mode simulation doesn't run a smart account's `__check_auth`, + // so its footprint and fee miss that call. Re-simulate with the signed + // entries to capture it. + if auth_signers + .iter() + .any(|s| matches!(s.kind, signer::SignerKind::Plugin(_))) + { + print.infoln("Re-simulating with smart account signatures…"); + let resimulated = simulate_and_assemble_transaction( + client, + &txn, + resources.resource_config(), + resources.resource_fee, + Some(soroban_rpc::AuthMode::Enforce), + ) + .await?; + assembled = resources.apply_to_assembled_txn(resimulated); + *txn = assembled.transaction().clone(); + } } let mut signed_tx = config.sign(*txn, quiet).await?;