Skip to main content

cast/cmd/tempo/zone/
signer.rs

1//! The sender of zone deposits and withdrawals, which also signs zone RPC authorization tokens.
2
3use crate::tempo::CAST_LOCAL_OWNERS_HINT;
4use alloy_consensus::SignableTransaction;
5use alloy_network::NetworkWallet;
6use alloy_primitives::{Address, B256, Bytes};
7use alloy_signer::Signer;
8use clap::Parser;
9use eyre::{Result, ensure};
10use foundry_cli::opts::TempoOpts;
11use foundry_common::{sh_status, tempo::configurable_account::ConfigurableAccountSigner};
12use foundry_config::Config;
13use foundry_wallets::{WalletOpts, WalletSigner};
14use tempo_alloy::{TempoNetwork, rpc::TempoTransactionRequest};
15use tempo_primitives::{TempoTxEnvelope, transaction::TempoTypedTransaction};
16
17/// Tempo configurable account options of the zone commands, as `cast send` takes them.
18#[derive(Clone, Debug, Default, Parser)]
19#[command(next_help_heading = "Configurable account (T14)")]
20pub(super) struct ConfigurableAccountOpts {
21    /// Send as this Tempo configurable account (T14), failing unless it is one.
22    ///
23    /// Not needed for a sender named with `--from` other than the wallet's key: a configurable
24    /// account sender is detected from Tempo L1, and the local owner keys (the wallet options,
25    /// `--tempo.owner`, and owner keys in the Tempo Accounts store) sign its `0x05` transactions
26    /// and zone RPC authorization tokens. An EOA upgraded to a configurable account names itself
27    /// here to withdraw.
28    #[arg(long = "tempo.configurable-account", value_name = "ADDRESS")]
29    configurable_account: Option<Address>,
30
31    /// The configuration of the configurable account sender, instead of rebuilding it from
32    /// Tempo L1.
33    ///
34    /// JSON, inline or in a file, as `cast wallet owners --json` prints it.
35    #[arg(long = "tempo.config", value_name = "CONFIG")]
36    config: Option<String>,
37
38    /// An owner key of the configurable account sender, in addition to the wallet options.
39    ///
40    /// Repeat for several owners. Takes the forms of `cast send --tempo.owner`.
41    #[arg(long = "tempo.owner", value_name = "SIGNER")]
42    owners: Vec<String>,
43
44    /// Send from the key itself instead of the Tempo configurable account linked to its
45    /// keystore.
46    #[arg(long, conflicts_with = "configurable_account")]
47    eoa: bool,
48}
49
50impl ConfigurableAccountOpts {
51    fn tempo(&self) -> TempoOpts {
52        TempoOpts {
53            configurable_account: self.configurable_account,
54            configurable_account_config: self.config.clone(),
55            owners: self.owners.clone(),
56            eoa: self.eoa,
57            ..Default::default()
58        }
59    }
60
61    /// Returns whether the sender may be a configurable account: the options select one,
62    /// `--from` names a sender other than the wallet's key `local`, or the wallet's keystore is
63    /// linked to one.
64    pub(super) fn may_select(
65        &self,
66        wallet: &WalletOpts,
67        local: Option<&WalletSigner>,
68    ) -> Result<bool> {
69        let tempo = self.tempo();
70        Ok(tempo.has_configurable_account_options()
71            || wallet.from.is_some_and(|from| local.is_none_or(|key| key.address() != from))
72            || tempo.linked_account(wallet)?.is_some())
73    }
74}
75
76/// Signs zone transactions and RPC authorization tokens as the wallet's key or, as `cast send`
77/// does, as the Tempo configurable account the sender is.
78#[derive(Debug)]
79pub(super) enum ZoneSigner {
80    Wallet(WalletSigner),
81    ConfigurableAccount(ConfigurableAccountSigner),
82}
83
84impl ZoneSigner {
85    /// Resolves the sender as `cast send` does from the wallet's key `signer`, detecting a
86    /// configurable account on the Tempo chain that `l1` connects to. Zones follow the account's
87    /// Tempo configuration (TIP-1154). Without `l1`, the wallet's key sends.
88    pub(super) async fn resolve(
89        wallet: &WalletOpts,
90        opts: &ConfigurableAccountOpts,
91        mut signer: Option<WalletSigner>,
92        l1: Option<&Config>,
93    ) -> Result<Self> {
94        if let Some(config) = l1 {
95            let account = opts
96                .tempo()
97                .configurable_account_signer(config, wallet, &mut signer, CAST_LOCAL_OWNERS_HINT)
98                .await?;
99            if let Some(account) = account {
100                sh_status!("Sending as Tempo configurable account {}", account.account())?;
101                return Ok(Self::ConfigurableAccount(account));
102            }
103        }
104        let signer = match signer {
105            Some(signer) => signer,
106            None => wallet.signer().await?,
107        };
108        if let Some(from) = wallet.from {
109            ensure!(from == signer.address(), "--from does not match the signing wallet");
110        }
111        Ok(Self::Wallet(signer))
112    }
113
114    /// The sender of the zone transactions and the caller the zone RPC authenticates.
115    pub(super) fn address(&self) -> Address {
116        match self {
117            Self::Wallet(signer) => signer.address(),
118            Self::ConfigurableAccount(account) => account.sender(),
119        }
120    }
121
122    /// Makes `tx` a Tempo transaction whose gas estimate models the owners' approvals, when the
123    /// sender is a configurable account.
124    pub(super) fn prepare(&self, mut tx: TempoTransactionRequest) -> TempoTransactionRequest {
125        if let Self::ConfigurableAccount(account) = self {
126            account.prepare_request::<TempoNetwork>(&mut tx);
127        }
128        tx
129    }
130
131    /// Signs a zone RPC token `digest`: a raw 65-byte secp256k1 signature for the wallet's key,
132    /// as `cast wallet sign --no-hash` makes, or the `0x05` owner quorum of a configurable
133    /// account, which approves `configurable_account_digest(digest, account, version)`.
134    pub(super) async fn sign_token_digest(&self, digest: B256) -> Result<Bytes> {
135        Ok(match self {
136            Self::Wallet(signer) => signer.sign_hash(&digest).await?.as_bytes().into(),
137            Self::ConfigurableAccount(account) => account.sign_hash(digest).await?.to_bytes(),
138        })
139    }
140}
141
142impl NetworkWallet<TempoNetwork> for ZoneSigner {
143    fn default_signer_address(&self) -> Address {
144        self.address()
145    }
146
147    fn has_signer_for(&self, address: &Address) -> bool {
148        *address == self.address()
149    }
150
151    fn signer_addresses(&self) -> impl Iterator<Item = Address> {
152        std::iter::once(self.address())
153    }
154
155    async fn sign_transaction_from(
156        &self,
157        sender: Address,
158        mut tx: TempoTypedTransaction,
159    ) -> alloy_signer::Result<TempoTxEnvelope> {
160        if sender != self.address() {
161            return Err(alloy_signer::Error::other(format!("no signer for {sender}")));
162        }
163        match self {
164            Self::Wallet(signer) => {
165                let signature = alloy_network::TxSigner::sign_transaction(signer, &mut tx).await?;
166                Ok(tx.into_signed(signature).into())
167            }
168            Self::ConfigurableAccount(account) => {
169                let TempoTypedTransaction::AA(tx) = tx else {
170                    return Err(alloy_signer::Error::other(
171                        "a configurable account only signs Tempo transactions",
172                    ));
173                };
174                let signature = account
175                    .sign_hash(tx.signature_hash())
176                    .await
177                    .map_err(|err| alloy_signer::Error::other(format!("{err:#}")))?;
178                Ok(TempoTxEnvelope::AA(tx.into_signed(signature)))
179            }
180        }
181    }
182}
183
184#[cfg(test)]
185mod tests {
186    use super::*;
187
188    #[derive(Parser)]
189    struct Args {
190        #[command(flatten)]
191        wallet: WalletOpts,
192        #[command(flatten)]
193        configurable_account: ConfigurableAccountOpts,
194    }
195
196    /// Withdrawals query Tempo L1 only for a sender that may be a configurable account, so that a
197    /// plain key, even named with `--from` or `ETH_FROM`, stays off a public L1 RPC.
198    #[tokio::test]
199    async fn only_possible_configurable_accounts_query_l1() {
200        let key = "0x6161616161616161616161616161616161616161616161616161616161616161";
201        let address = WalletSigner::from_private_key(&key.parse().unwrap()).unwrap().address();
202        let (address, other) = (address.to_string(), Address::repeat_byte(1).to_string());
203        let config = r#"{"salt":"0x00","version":0,"threshold":1,"owners":[]}"#;
204        for (args, expected) in [
205            (&[][..], false),
206            (&["--private-key", key], false),
207            (&["--private-key", key, "--from", &address], false),
208            (&["--private-key", key, "--eoa"], false),
209            (&["--private-key", key, "--from", &other], true),
210            (&["--from", &other], true),
211            (&["--tempo.configurable-account", &other], true),
212            (&["--tempo.config", config], true),
213            (&["--tempo.owner", "env://OWNER"], true),
214        ] {
215            let args =
216                Args::try_parse_from(std::iter::once("zone").chain(args.iter().copied())).unwrap();
217            let local = args.wallet.maybe_signer().await.unwrap().0;
218            let selected = args.configurable_account.may_select(&args.wallet, local.as_ref());
219            assert_eq!(selected.unwrap(), expected, "{args:?}", args = args.wallet);
220        }
221    }
222}