Skip to main content

foundry_common/tempo/
configurable_account.rs

1//! Tempo configurable accounts (T14: TIP-1107, TIP-1113).
2//!
3//! Configurations are never stored locally. They are rebuilt from the chain: the latest
4//! `ConfigurableAccountConfigUpdated` or `AccountUpgraded` event of an account carries its full
5//! configuration, and its commitment must match `getConfigCommitment`. A 1-of-1, salt-0 account
6//! is recomputed from its owner key instead, which also covers accounts that have not sent their
7//! first transaction yet.
8//!
9//! `cast wallet` reads and updates configurations with these helpers and combines owner approvals,
10//! including WebAuthn assertions made in a browser, into `0x05` signatures.
11//!
12//! [`detect_configurable_account`] tells whether a sender is a configurable account, and
13//! [`ConfigurableAccountSigner`] signs its transactions with `0x05` signatures from local owner
14//! keys.
15
16use crate::FoundryTransactionBuilder;
17use alloy_consensus::BlockHeader;
18use alloy_network::{BlockResponse, Network, TransactionBuilder};
19use alloy_primitives::{Address, B256, Bytes, U256, hex};
20use alloy_provider::Provider;
21use alloy_rpc_types::{BlockId, BlockNumberOrTag, Filter, Log};
22use alloy_signer::Signer;
23use alloy_sol_types::{SolCall, SolEvent};
24use base64::{
25    Engine,
26    alphabet::URL_SAFE,
27    engine::{DecodePaddingMode, GeneralPurpose, GeneralPurposeConfig},
28};
29use eyre::{Context, Result};
30use foundry_wallets::WalletSigner;
31use p256::ecdsa::signature::hazmat::PrehashSigner;
32use serde::{Deserialize, Serialize};
33use serde_json::Value;
34use std::{
35    collections::BTreeMap,
36    ffi::OsString,
37    path::{Path, PathBuf},
38    sync::Arc,
39};
40use tempo_alloy::{
41    TempoNetwork,
42    accounts::{TempoAccessKey, TempoAccountsStore, TempoAccountsWallet},
43    contracts::precompiles::{
44        CONFIGURABLE_ACCOUNT_ADDRESS,
45        IConfigurableAccount::{
46            self, AccountUpgraded, ConfigurableAccountConfigUpdated,
47            ConfigurableAccountOwner as AbiOwner,
48        },
49    },
50    rpc::{
51        ConfigurableAccountSimulationApproval, ConfigurableAccountSimulationSpec,
52        PrimitiveSignatureType, TempoTransactionRequest,
53    },
54};
55use tempo_primitives::{
56    SignatureType, TempoTxEnvelope,
57    transaction::{
58        ConfigurableAccountConfig, ConfigurableAccountOwner, ConfigurableAccountSignature,
59        KeychainSignature, MAX_CONFIGURABLE_ACCOUNT_SIGNATURES, PrimitiveSignature,
60        TEMPO_TX_TYPE_ID, TempoSignature, TempoTransaction, configurable_account_digest,
61        tt_signature::{P256SignatureWithPreHash, WebAuthnSignature},
62    },
63};
64
65pub use foundry_common_fmt::ConfigJson;
66
67/// Blocks per `eth_getLogs` request when a configuration lookup starts. The window is halved
68/// whenever the RPC rejects a request, which covers providers that cap the block range or the
69/// number of results.
70const LOG_LOOKUP_WINDOW: u64 = 100_000;
71
72/// The error for a configurable account operation on a chain before T14.
73const T14_REQUIRED: &str =
74    "configurable accounts require the Tempo T14 hardfork, which is not active on this chain";
75
76/// Converts a Tempo configurable account error, which is not a `std::error::Error`.
77pub fn ca_error(err: impl std::fmt::Display) -> eyre::Report {
78    eyre::eyre!("{err}")
79}
80
81/// Returns the 1-of-1, salt-0 configuration that `cast wallet new` creates for `owner`.
82pub fn single_owner_config(owner: Address) -> ConfigurableAccountConfig {
83    ConfigurableAccountConfig {
84        salt: B256::ZERO,
85        version: 0,
86        threshold: 1,
87        owners: vec![ConfigurableAccountOwner { owner, weight: 1 }],
88    }
89}
90
91/// Returns the account address of the 1-of-1, salt-0 configuration for `owner`.
92pub fn single_owner_account(owner: Address) -> Result<Address> {
93    single_owner_config(owner).derive_account().map_err(ca_error)
94}
95
96/// Returns the configuration commitment of `account` at `block`, or `None` when the configurable
97/// account precompile is not active there: before T14 a call to it returns no data.
98pub async fn config_commitment<P: Provider<TempoNetwork>>(
99    provider: &P,
100    account: Address,
101    block: BlockId,
102) -> Result<Option<B256>> {
103    let request = TempoTransactionRequest::default()
104        .with_to(CONFIGURABLE_ACCOUNT_ADDRESS)
105        .with_input(IConfigurableAccount::getConfigCommitmentCall { account }.abi_encode());
106    let output = provider.call(request).block(block).await?;
107    if output.is_empty() {
108        return Ok(None);
109    }
110    Ok(Some(IConfigurableAccount::getConfigCommitmentCall::abi_decode_returns(&output)?))
111}
112
113/// Returns the current configuration of `account`, rebuilt from the chain.
114///
115/// `keys` are owner addresses whose 1-of-1, salt-0 configuration is tried first. Returns `None`
116/// when the account has no registered configuration and none of `keys` derives it. Fails before
117/// T14.
118pub async fn current_config<P: Provider<TempoNetwork>>(
119    provider: &P,
120    account: Address,
121    keys: &[Address],
122) -> Result<Option<ConfigurableAccountConfig>> {
123    let block = BlockId::latest();
124    let commitment = config_commitment(provider, account, block)
125        .await?
126        .ok_or_else(|| eyre::eyre!(T14_REQUIRED))?;
127    config_for_commitment(provider, account, keys, commitment, block).await
128}
129
130/// Tells whether `account` is a configurable account at `block`, and returns its configuration
131/// there.
132///
133/// The account is one when it has a registered configuration commitment (a derived account after
134/// its first transaction, or an upgraded EOA), or when one of the local owner `keys` derives it as
135/// a 1-of-1, salt-0 account. `config` overrides the lookup: it is checked against the commitment,
136/// or against the account address for an account that has not sent its first transaction.
137///
138/// Returns `None` before T14 and for an account that is not a configurable account, unless
139/// `required` is set or `config` is given, which fail instead. A sender that is itself one of
140/// `keys` is also taken as a plain key when the RPC cannot be reached, so that fully specified
141/// transactions still sign offline.
142pub async fn detect_configurable_account<P: Provider<TempoNetwork>>(
143    provider: &P,
144    account: Address,
145    keys: &[Address],
146    config: Option<ConfigurableAccountConfig>,
147    required: bool,
148    block: BlockId,
149) -> Result<Option<ConfigurableAccountConfig>> {
150    let required = required || config.is_some();
151    let commitment = match config_commitment(provider, account, block).await {
152        Err(error) if !required && keys.contains(&account) => {
153            tracing::debug!(%error, %account, "cannot tell whether the sender is a configurable account");
154            return Ok(None);
155        }
156        commitment => commitment?,
157    };
158    let Some(commitment) = commitment else {
159        eyre::ensure!(!required, T14_REQUIRED);
160        return Ok(None);
161    };
162    if let Some(config) = config {
163        check_config(account, &config, commitment)?;
164        return Ok(Some(config));
165    }
166    let config = config_for_commitment(provider, account, keys, commitment, block).await?;
167    eyre::ensure!(
168        config.is_some() || !required,
169        "{account} is not a configurable account: it has no registered configuration, and no \
170         local owner key derives it. Pass its configuration with --tempo.config if it has not \
171         sent its first transaction yet"
172    );
173    Ok(config)
174}
175
176/// Tells whether `config` is still the configuration of `account` at the latest block. Fails when
177/// the commitment cannot be read, so that a failing RPC is not taken for a changed configuration.
178pub async fn has_config<P: Provider<TempoNetwork>>(
179    provider: &P,
180    account: Address,
181    config: &ConfigurableAccountConfig,
182) -> Result<bool> {
183    let commitment = config_commitment(provider, account, BlockId::latest())
184        .await?
185        .ok_or_else(|| eyre::eyre!(T14_REQUIRED))?;
186    Ok(check_config(account, config, commitment).is_ok())
187}
188
189/// Checks that `config` is the current configuration of `account`, whose stored commitment is
190/// `commitment`.
191fn check_config(
192    account: Address,
193    config: &ConfigurableAccountConfig,
194    commitment: B256,
195) -> Result<()> {
196    if commitment.is_zero() {
197        eyre::ensure!(
198            config.version == 0 && config.derive_account().map_err(ca_error)? == account,
199            "the given configuration does not derive {account}, which has no registered \
200             configuration"
201        );
202    } else {
203        eyre::ensure!(
204            config.commitment().map_err(ca_error)? == commitment,
205            "the given configuration does not match the configuration commitment {commitment} \
206             of {account}"
207        );
208    }
209    Ok(())
210}
211
212/// Returns the configuration of `account` that matches its `commitment` stored at `block`.
213async fn config_for_commitment<P: Provider<TempoNetwork>>(
214    provider: &P,
215    account: Address,
216    keys: &[Address],
217    commitment: B256,
218    block: BlockId,
219) -> Result<Option<ConfigurableAccountConfig>> {
220    for key in keys {
221        let config = single_owner_config(*key);
222        let matches = if commitment.is_zero() {
223            config.derive_account().ok() == Some(account)
224        } else {
225            config.commitment().ok() == Some(commitment)
226        };
227        if matches {
228            return Ok(Some(config));
229        }
230    }
231    if commitment.is_zero() {
232        return Ok(None);
233    }
234    // The log scan starts at `block`, so that a later configuration change is not taken.
235    let block = match block {
236        BlockId::Number(BlockNumberOrTag::Number(number)) => number,
237        BlockId::Number(BlockNumberOrTag::Latest) => provider.get_block_number().await?,
238        block => provider
239            .get_block(block)
240            .await?
241            .ok_or_else(|| eyre::eyre!("block {block} not found"))?
242            .header()
243            .number(),
244    };
245    config_from_logs(provider, account, commitment, block).await.map(Some)
246}
247
248/// Scans the configurable account precompile's logs backwards from `block` for the latest
249/// configuration event of `account`, which must match `commitment`.
250pub async fn config_from_logs<N: Network, P: Provider<N>>(
251    provider: &P,
252    account: Address,
253    commitment: B256,
254    block: u64,
255) -> Result<ConfigurableAccountConfig> {
256    let mut to = block;
257    let mut window = LOG_LOOKUP_WINDOW;
258    loop {
259        let from = to.saturating_sub(window - 1);
260        let filter = Filter::new()
261            .address(CONFIGURABLE_ACCOUNT_ADDRESS)
262            .event_signature(vec![
263                ConfigurableAccountConfigUpdated::SIGNATURE_HASH,
264                AccountUpgraded::SIGNATURE_HASH,
265            ])
266            .topic1(account.into_word())
267            .from_block(from)
268            .to_block(to);
269        let logs = match provider.get_logs(&filter).await {
270            Ok(logs) => logs,
271            // RPCs reject ranges or result sets above their limits with JSON-RPC errors of
272            // varied wording. Transport and HTTP failures, such as auth errors, fail at once.
273            Err(err) if window > 1 && err.as_error_resp().is_some() => {
274                window /= 2;
275                continue;
276            }
277            Err(err) => {
278                return Err(err).wrap_err(format!(
279                    "failed to read the configuration events of {account} at block {to}"
280                ));
281            }
282        };
283        // Every configuration change emits an event, so the latest one is the current
284        // configuration.
285        if let Some(log) = logs.iter().rev().find_map(|log| config_from_log(log).transpose()) {
286            let config = log?;
287            eyre::ensure!(
288                config.commitment().map_err(ca_error)? == commitment,
289                "the latest configuration event of {account} does not match its commitment \
290                 {commitment}"
291            );
292            return Ok(config);
293        }
294        if from == 0 {
295            eyre::bail!(
296                "{account} has the configuration commitment {commitment}, but no configuration \
297                 event was found"
298            );
299        }
300        to = from - 1;
301    }
302}
303
304/// Rebuilds the configuration that a configuration event announces.
305fn config_from_log(log: &Log) -> Result<Option<ConfigurableAccountConfig>> {
306    let owners = |owners: Vec<AbiOwner>| {
307        owners
308            .into_iter()
309            .map(|owner| ConfigurableAccountOwner { owner: owner.owner, weight: owner.weight })
310            .collect()
311    };
312    let config = match log.topic0() {
313        Some(&ConfigurableAccountConfigUpdated::SIGNATURE_HASH) => {
314            let event = ConfigurableAccountConfigUpdated::decode_log_data(log.data())?;
315            ConfigurableAccountConfig {
316                salt: event.salt,
317                version: event.version,
318                threshold: event.threshold,
319                owners: owners(event.owners),
320            }
321        }
322        // TIP-1113 installs version one.
323        Some(&AccountUpgraded::SIGNATURE_HASH) => {
324            let event = AccountUpgraded::decode_log_data(log.data())?;
325            ConfigurableAccountConfig {
326                salt: event.salt,
327                version: 1,
328                threshold: event.threshold,
329                owners: owners(event.owners),
330            }
331        }
332        _ => return Ok(None),
333    };
334    Ok(Some(config))
335}
336
337/// Returns `config`'s owners as `IConfigurableAccount` encodes them.
338pub fn abi_owners(config: &ConfigurableAccountConfig) -> Vec<AbiOwner> {
339    config
340        .owners
341        .iter()
342        .map(|owner| AbiOwner { owner: owner.owner, weight: owner.weight })
343        .collect()
344}
345
346/// Returns the owner quorum that gas estimation models for `account`: the owners in
347/// `approvals` with their key types or, when it is empty, the most approvals any valid signing
348/// set can need, as maximum-size `WebAuthn` approvals.
349pub fn simulation_spec(
350    account: Address,
351    config: &ConfigurableAccountConfig,
352    approvals: &[(Address, PrimitiveSignatureType)],
353) -> ConfigurableAccountSimulationSpec {
354    let mut approvals = if approvals.is_empty() {
355        quorum(&config.owners, config.threshold, true)
356            .into_iter()
357            .map(|owner| ConfigurableAccountSimulationApproval {
358                owner,
359                key_type: None,
360                key_data: None,
361            })
362            .collect::<Vec<_>>()
363    } else {
364        approvals
365            .iter()
366            .map(|(owner, key_type)| ConfigurableAccountSimulationApproval {
367                owner: *owner,
368                key_type: Some(*key_type),
369                key_data: None,
370            })
371            .collect()
372    };
373    approvals.sort_by_key(|approval| approval.owner);
374    ConfigurableAccountSimulationSpec { signer: Some(account), config: config.clone(), approvals }
375}
376
377/// Makes `tx` a Tempo transaction from `account`, whose gas estimate models the owner quorum of
378/// `spec`. A `0x05` signature only signs Tempo (`0x76`) transactions.
379pub fn prepare_request<N: Network>(
380    tx: &mut N::TransactionRequest,
381    account: Address,
382    spec: ConfigurableAccountSimulationSpec,
383) where
384    N::TransactionRequest: FoundryTransactionBuilder<N>,
385{
386    tx.set_from(account);
387    if tx.nonce_key().is_none() {
388        tx.set_nonce_key(U256::ZERO);
389    }
390    tx.set_configurable_account_simulation(spec);
391}
392
393/// Tells whether a call to `to` with `input` updates the configuration of the account that sends
394/// it.
395pub fn updates_config(to: Option<Address>, input: Option<&Bytes>) -> bool {
396    to == Some(CONFIGURABLE_ACCOUNT_ADDRESS)
397        && input.is_some_and(|input| {
398            input.starts_with(&IConfigurableAccount::updateConfigCall::SELECTOR)
399        })
400}
401
402/// Returns the largest owner quorum among `owners`, or the smallest one unless `largest` is set,
403/// that the node accepts: at most [`MAX_CONFIGURABLE_ACCOUNT_SIGNATURES`] owners that, in address
404/// order, reach `threshold` only on the last one. `owners` are sorted by address. Returns an empty
405/// list when no quorum exists.
406pub fn quorum(owners: &[ConfigurableAccountOwner], threshold: u8, largest: bool) -> Vec<Address> {
407    let threshold = usize::from(threshold);
408    // `reach[i][k][w]`: `k` of the first `i` owners weigh `w`, below the threshold.
409    let mut reach = vec![[[false; 256]; MAX_CONFIGURABLE_ACCOUNT_SIGNATURES]; owners.len() + 1];
410    reach[0][0][0] = true;
411    for (i, owner) in owners.iter().enumerate() {
412        let weight = usize::from(owner.weight);
413        reach[i + 1] = reach[i];
414        for k in 0..MAX_CONFIGURABLE_ACCOUNT_SIGNATURES - 1 {
415            for w in 0..threshold.saturating_sub(weight) {
416                if reach[i][k][w] {
417                    reach[i + 1][k + 1][w + weight] = true;
418                }
419            }
420        }
421    }
422
423    // The last owner in address order completes the quorum from below the threshold.
424    let mut best = None;
425    for (last, owner) in owners.iter().enumerate() {
426        for (k, weights) in reach[last].iter().enumerate() {
427            let below = threshold.saturating_sub(usize::from(owner.weight))..threshold;
428            if let Some(w) = below.into_iter().find(|&w| weights[w])
429                && best.is_none_or(|(best_k, _, _)| if largest { k > best_k } else { k < best_k })
430            {
431                best = Some((k, last, w));
432            }
433        }
434    }
435    let Some((mut k, last, mut w)) = best else { return Vec::new() };
436
437    let mut quorum = vec![owners[last].owner];
438    for i in (0..last).rev() {
439        if k == 0 {
440            break;
441        }
442        // Owner `i` is in the quorum when the first `i` owners alone cannot weigh `w`.
443        if !reach[i][k][w] {
444            quorum.push(owners[i].owner);
445            k -= 1;
446            w -= usize::from(owners[i].weight);
447        }
448    }
449    quorum.reverse();
450    quorum
451}
452
453/// Tells whether owners among `keys` can approve for an account with `config`, as
454/// [`ConfigurableAccountSigner::new`] selects them.
455pub fn reaches_threshold(config: &ConfigurableAccountConfig, keys: &[Address]) -> bool {
456    let local = config
457        .owners
458        .iter()
459        .filter(|owner| keys.contains(&owner.owner))
460        .cloned()
461        .collect::<Vec<_>>();
462    !quorum(&local, config.threshold, false).is_empty()
463}
464
465/// Combines owner approvals of `inner` into a `0x05` signature for `account`.
466///
467/// Approvals are recovered and deduplicated, and the fewest that reach the threshold are kept,
468/// sorted by owner, as the node requires: in address order the last one reaches the threshold,
469/// and there are at most [`MAX_CONFIGURABLE_ACCOUNT_SIGNATURES`].
470pub fn combine_approvals(
471    account: Address,
472    config: &ConfigurableAccountConfig,
473    inner: B256,
474    approvals: Vec<PrimitiveSignature>,
475) -> Result<ConfigurableAccountSignature> {
476    let digest = configurable_account_digest(inner, account, config.version);
477    let mut by_owner = BTreeMap::new();
478    for (index, approval) in approvals.into_iter().enumerate() {
479        let owner = approval.recover_signer(&digest).map_err(|_| {
480            eyre::eyre!(
481                "signature {} does not verify against the owner digest {digest}; owners sign it \
482                 with `cast wallet sign --no-hash {digest}`, adding `--p256` for a raw P-256 owner",
483                index + 1
484            )
485        })?;
486        eyre::ensure!(
487            config.owner_weight(owner).is_some(),
488            "signature {} is from {owner}, which is not an owner of {account}",
489            index + 1
490        );
491        by_owner.insert(owner, approval);
492    }
493
494    let approvers = config
495        .owners
496        .iter()
497        .filter(|owner| by_owner.contains_key(&owner.owner))
498        .cloned()
499        .collect::<Vec<_>>();
500    let selected = quorum(&approvers, config.threshold, false);
501    if selected.is_empty() {
502        let weight = approvers.iter().map(|owner| u16::from(owner.weight)).sum::<u16>();
503        eyre::ensure!(
504            weight < u16::from(config.threshold),
505            "no {MAX_CONFIGURABLE_ACCOUNT_SIGNATURES} of the approvals reach the threshold {} of \
506             {account}",
507            config.threshold
508        );
509        eyre::bail!(
510            "the approvals reach weight {weight}, but {account} requires {}",
511            config.threshold
512        );
513    }
514    let mut signatures = Vec::new();
515    for (owner, approval) in by_owner {
516        if selected.contains(&owner) {
517            signatures.push(approval);
518        } else {
519            sh_status!("Dropped the approval of {owner}: the threshold is reached without it")?;
520        }
521    }
522
523    let signature = ConfigurableAccountSignature::try_new(account, config.clone(), signatures)
524        .map_err(ca_error)?;
525    signature.verify_approvals(inner).map_err(ca_error)?;
526    Ok(signature)
527}
528
529/// Parses an owner approval: a hex Tempo primitive signature (65-byte secp256k1, `0x01` P-256 or
530/// `0x02` WebAuthn), a JSON signature, or a WebAuthn assertion made in a browser. A value naming
531/// an existing file is read from it.
532pub fn parse_owner_signature(value: &str) -> Result<PrimitiveSignature> {
533    let value = value.trim();
534    if !value.starts_with('{') && !value.starts_with("0x") && Path::new(value).is_file() {
535        let contents = crate::fs::read_to_string(value)?;
536        return parse_owner_signature(&contents)
537            .wrap_err_with(|| format!("invalid owner signature in {value}"));
538    }
539    if value.starts_with('{') {
540        let json = serde_json::from_str::<Value>(value).wrap_err("invalid JSON signature")?;
541        return if json.get("response").is_some() || json.get("authenticatorData").is_some() {
542            parse_webauthn_assertion(&json)
543        } else {
544            Ok(serde_json::from_value(json).wrap_err("invalid JSON signature")?)
545        };
546    }
547    let bytes = hex::decode(value).wrap_err("invalid hex signature")?;
548    PrimitiveSignature::from_bytes(&bytes).map_err(|err| eyre::eyre!("invalid signature: {err}"))
549}
550
551/// Parses a browser WebAuthn assertion: `authenticatorData`, `clientDataJSON` and `signature`
552/// (an `AuthenticatorAssertionResponse`, at the top level or under `response` as
553/// `PublicKeyCredential.toJSON()` writes it), plus the credential's P-256 `publicKey`. Binary
554/// fields are base64url or 0x-prefixed hex; the signature is DER or raw `r || s`.
555fn parse_webauthn_assertion(json: &Value) -> Result<PrimitiveSignature> {
556    let field = |name: &str| -> Result<Vec<u8>> {
557        let value = json
558            .get(name)
559            .or_else(|| json.get("response").and_then(|response| response.get(name)))
560            .and_then(Value::as_str)
561            .ok_or_else(|| eyre::eyre!("the WebAuthn assertion has no `{name}` string"))?;
562        if name == "clientDataJSON" && value.starts_with('{') {
563            return Ok(value.as_bytes().to_vec());
564        }
565        // 0x-prefixed hex, or base64url with or without padding.
566        let decoded = if value.starts_with("0x") {
567            hex::decode(value).map_err(eyre::Report::from)
568        } else {
569            const BASE64URL: GeneralPurpose = GeneralPurpose::new(
570                &URL_SAFE,
571                GeneralPurposeConfig::new()
572                    .with_decode_padding_mode(DecodePaddingMode::Indifferent),
573            );
574            BASE64URL.decode(value).map_err(eyre::Report::from)
575        };
576        decoded.wrap_err_with(|| format!("invalid `{name}`"))
577    };
578
579    let public_key = field("publicKey")?;
580    let point = match public_key.len() {
581        64 => &public_key[..],
582        // Uncompressed SEC1 point, alone or at the end of a P-256 SubjectPublicKeyInfo.
583        65 | 91 if public_key[public_key.len() - 65] == 0x04 => {
584            &public_key[public_key.len() - 64..]
585        }
586        len => eyre::bail!("unsupported WebAuthn public key of {len} bytes"),
587    };
588
589    let signature = field("signature")?;
590    // A raw `r || s` can start with the DER tag 0x30, so the first byte cannot tell them apart.
591    let signature = p256::ecdsa::Signature::from_der(&signature)
592        .or_else(|_| p256::ecdsa::Signature::from_slice(&signature))
593        .map_err(|_| eyre::eyre!("invalid WebAuthn signature"))?;
594    // Tempo only accepts low-s P-256 signatures, which browsers do not guarantee.
595    let signature = signature.normalize_s().unwrap_or(signature);
596    let (r, s) = signature.split_bytes();
597
598    let mut webauthn_data = field("authenticatorData")?;
599    webauthn_data.extend(field("clientDataJSON")?);
600    Ok(PrimitiveSignature::WebAuthn(WebAuthnSignature {
601        r: B256::from_slice(&r),
602        s: B256::from_slice(&s),
603        pub_key_x: B256::from_slice(&point[..32]),
604        pub_key_y: B256::from_slice(&point[32..]),
605        webauthn_data: Bytes::from(webauthn_data),
606    }))
607}
608
609/// Parses a hex P-256 private key.
610pub fn parse_p256_key(private_key: &str) -> Result<p256::ecdsa::SigningKey> {
611    hex::decode(private_key.trim())
612        .ok()
613        .filter(|key| key.len() == 32)
614        .and_then(|key| p256::ecdsa::SigningKey::from_slice(&key).ok())
615        .ok_or_else(|| eyre::eyre!("invalid P-256 private key: expected a 32-byte hex scalar"))
616}
617
618/// Signs the prehash `message` with the P-256 `key` and returns a low-s `(r, s)`, which Tempo's
619/// verifier requires and about half of raw ECDSA signatures are not.
620pub fn sign_p256_low_s(
621    key: &p256::ecdsa::SigningKey,
622    message: &[u8],
623) -> Result<(B256, B256), p256::ecdsa::Error> {
624    let signature: p256::ecdsa::Signature = key.sign_prehash(message)?;
625    let signature = signature.normalize_s().unwrap_or(signature);
626    let (r, s) = signature.split_bytes();
627    Ok((B256::from_slice(&r), B256::from_slice(&s)))
628}
629
630/// Returns the affine coordinates of the public key of the P-256 `key`.
631pub fn p256_public_key(key: &p256::ecdsa::SigningKey) -> (B256, B256) {
632    let point = key.verifying_key().to_encoded_point(false);
633    (B256::from_slice(point.x().unwrap()), B256::from_slice(point.y().unwrap()))
634}
635
636/// Signs `digest` with the P-256 `key` as the `0x01` approval of a raw P-256 owner. The signature
637/// covers `digest` itself, without the SHA-256 pre-hash of WebCrypto keys.
638pub fn sign_p256(
639    key: &p256::ecdsa::SigningKey,
640    digest: &B256,
641) -> Result<PrimitiveSignature, p256::ecdsa::Error> {
642    let (r, s) = sign_p256_low_s(key, digest.as_slice())?;
643    let (pub_key_x, pub_key_y) = p256_public_key(key);
644    Ok(PrimitiveSignature::P256(P256SignatureWithPreHash {
645        r,
646        s,
647        pub_key_x,
648        pub_key_y,
649        pre_hash: false,
650    }))
651}
652
653/// Parses a configuration given as JSON, or as the path of a JSON file: `salt`, `version`,
654/// `threshold` and `owners` (each an `owner` and a `weight`), as `cast wallet owners --json`
655/// prints it, with or without its JSON envelope.
656pub fn parse_config(value: &str) -> Result<ConfigurableAccountConfig> {
657    let value = value.trim();
658    let json = if !value.starts_with('{') && Path::new(value).is_file() {
659        crate::fs::read_to_string(value)?
660    } else {
661        value.to_string()
662    };
663    let mut json = serde_json::from_str::<serde_json::Value>(&json)
664        .wrap_err("invalid configurable account configuration JSON")?;
665    if let Some(data) = json.get_mut("data") {
666        json = data.take();
667    }
668    serde_json::from_value::<ConfigJson>(json)
669        .wrap_err("invalid configurable account configuration")?
670        .try_into()
671}
672
673/// Decodes an unsigned Tempo transaction as `cast mktx --raw-unsigned` encodes it.
674pub fn decode_unsigned_tx(bytes: &[u8]) -> Result<TempoTransaction> {
675    let Some((&TEMPO_TX_TYPE_ID, mut fields)) = bytes.split_first() else {
676        eyre::bail!(
677            "expected an unsigned Tempo (0x76) transaction from `cast mktx --raw-unsigned`"
678        );
679    };
680    let tx = <TempoTransaction as alloy_rlp::Decodable>::decode(&mut fields).map_err(|_| {
681        eyre::eyre!("invalid unsigned Tempo transaction; sponsored transactions are not supported")
682    })?;
683    eyre::ensure!(fields.is_empty(), "trailing bytes after the unsigned Tempo transaction");
684    Ok(tx)
685}
686
687/// A local key that approves the transactions of the configurable accounts it owns.
688#[derive(Clone, Debug)]
689pub enum ConfigurableAccountOwnerKey {
690    /// A Foundry wallet: a private key, keystore, hardware wallet or remote signer.
691    Wallet(Arc<WalletSigner>),
692    /// A locally signable key from the Tempo Accounts store.
693    Accounts(Box<TempoAccessKey>),
694}
695
696impl ConfigurableAccountOwnerKey {
697    /// The owner address of the key.
698    pub fn address(&self) -> Address {
699        match self {
700            Self::Wallet(signer) => signer.address(),
701            Self::Accounts(key) => key.address(),
702        }
703    }
704
705    /// The signature type of the key's approvals.
706    const fn key_type(&self) -> PrimitiveSignatureType {
707        match self {
708            Self::Wallet(_) => PrimitiveSignatureType::Secp256k1,
709            Self::Accounts(key) => match key.signature_type() {
710                SignatureType::P256 => PrimitiveSignatureType::P256,
711                SignatureType::WebAuthn => PrimitiveSignatureType::WebAuthn,
712                _ => PrimitiveSignatureType::Secp256k1,
713            },
714        }
715    }
716
717    /// Approves `digest`.
718    pub async fn sign(&self, digest: &B256) -> Result<PrimitiveSignature> {
719        Ok(match self {
720            Self::Wallet(signer) => PrimitiveSignature::Secp256k1(signer.sign_hash(digest).await?),
721            Self::Accounts(key) => key.sign_hash(digest).await?,
722        })
723    }
724}
725
726impl From<WalletSigner> for ConfigurableAccountOwnerKey {
727    fn from(signer: WalletSigner) -> Self {
728        Self::Wallet(Arc::new(signer))
729    }
730}
731
732/// Returns the locally signable keys of the Tempo Accounts store on `chain_id` that own
733/// `config`. A missing or unreadable store has none.
734pub fn stored_owner_keys(
735    chain_id: u64,
736    config: &ConfigurableAccountConfig,
737) -> Vec<ConfigurableAccountOwnerKey> {
738    let stored = || -> Result<Vec<ConfigurableAccountOwnerKey>> {
739        let Some(store) = TempoAccountsStore::try_open_default()? else { return Ok(Vec::new()) };
740        let wallet = TempoAccountsWallet::from_store(store.path())?;
741        Ok(store
742            .access_keys()?
743            .into_iter()
744            .filter(|key| {
745                key.chain_id() == chain_id
746                    && key.is_locally_signable()
747                    && config.owner_weight(key.address()).is_some()
748            })
749            .filter_map(|key| wallet.access_key(key.account(), chain_id, key.address()).ok())
750            .map(|key| ConfigurableAccountOwnerKey::Accounts(Box::new(key)))
751            .collect())
752    };
753    stored().unwrap_or_else(|error| {
754        tracing::warn!(%error, "failed to read owner keys from the Tempo Accounts store");
755        Vec::new()
756    })
757}
758
759/// Signs the transactions of a configurable account with `0x05` signatures from local owner keys,
760/// or, as an access key of another account (TIP-1111), with keychain V2 signatures that wrap them.
761#[derive(Clone, Debug)]
762pub struct ConfigurableAccountSigner {
763    account: Address,
764    config: ConfigurableAccountConfig,
765    /// The approving owners, sorted by address, whose weight reaches the threshold.
766    owners: Vec<ConfigurableAccountOwnerKey>,
767    /// The account that the configurable account signs for as an access key, if any.
768    parent: Option<Address>,
769}
770
771impl ConfigurableAccountSigner {
772    /// Selects the owners among `keys` that approve for `account`.
773    ///
774    /// Owners are taken in ascending address order, as the node requires, until their weight
775    /// reaches the threshold; keys that are not owners are ignored. When the local owners do not
776    /// reach the threshold, the error names the owners and ends with `hint`, which says how to
777    /// provide the others.
778    pub fn new(
779        account: Address,
780        config: ConfigurableAccountConfig,
781        keys: impl IntoIterator<Item = ConfigurableAccountOwnerKey>,
782        hint: &str,
783    ) -> Result<Self> {
784        let mut keys = keys.into_iter().map(|key| (key.address(), key)).collect::<BTreeMap<_, _>>();
785        let local = config
786            .owners
787            .iter()
788            .filter(|owner| keys.contains_key(&owner.owner))
789            .cloned()
790            .collect::<Vec<_>>();
791        // The fewest local owners that the node accepts, as `combine_approvals` selects them.
792        let selected = quorum(&local, config.threshold, false);
793        if selected.is_empty() {
794            let weight = local.iter().map(|owner| u16::from(owner.weight)).sum::<u16>();
795            let local = if local.is_empty() {
796                "no local key is an owner".to_string()
797            } else {
798                let keys = local.iter().map(|owner| owner.owner.to_string()).collect::<Vec<_>>();
799                let keys = keys.join(", ");
800                if weight < u16::from(config.threshold) {
801                    format!("the local owner keys {keys} reach weight {weight}")
802                } else {
803                    format!(
804                        "no {MAX_CONFIGURABLE_ACCOUNT_SIGNATURES} of the local owner keys {keys} \
805                         reach it"
806                    )
807                }
808            };
809            let all = config
810                .owners
811                .iter()
812                .map(|owner| format!("{} (weight {})", owner.owner, owner.weight))
813                .collect::<Vec<_>>();
814            eyre::bail!(
815                "{account} is a Tempo configurable account that needs owner weight {}, but \
816                 {local}. Its owners are {}. {hint}",
817                config.threshold,
818                all.join(", "),
819            );
820        }
821        let owners = selected.iter().filter_map(|owner| keys.remove(owner)).collect();
822        Ok(Self { account, config, owners, parent: None })
823    }
824
825    /// Signs as an access key of `parent`, which authorized the account with key type
826    /// `configurable` (TIP-1111).
827    pub const fn with_parent(mut self, parent: Address) -> Self {
828        self.parent = Some(parent);
829        self
830    }
831
832    /// The configurable account.
833    pub const fn account(&self) -> Address {
834        self.account
835    }
836
837    /// The transaction sender: the account the access key signs for, else the configurable
838    /// account itself.
839    pub fn sender(&self) -> Address {
840        self.parent.unwrap_or(self.account)
841    }
842
843    /// The account's current configuration.
844    pub const fn config(&self) -> &ConfigurableAccountConfig {
845        &self.config
846    }
847
848    /// The owner quorum that gas estimation models: the selected owners with their key types.
849    pub fn simulation_spec(&self) -> ConfigurableAccountSimulationSpec {
850        let approvals =
851            self.owners.iter().map(|key| (key.address(), key.key_type())).collect::<Vec<_>>();
852        simulation_spec(self.account, &self.config, &approvals)
853    }
854
855    /// Makes `tx` a Tempo transaction from the sender, whose gas estimate models the owners'
856    /// approvals. As an access key, the account is the request's `keyId`, so the node models its
857    /// quorum inside a keychain signature.
858    pub fn prepare_request<N: Network>(&self, tx: &mut N::TransactionRequest)
859    where
860        N::TransactionRequest: FoundryTransactionBuilder<N>,
861    {
862        prepare_request::<N>(tx, self.sender(), self.simulation_spec());
863        if self.parent.is_some() {
864            tx.set_key_id(self.account);
865        }
866    }
867
868    /// Signs a filled request with the owners' approvals of its signature hash, as
869    /// [`Self::sign_hash`] does.
870    pub async fn sign_request(&self, request: TempoTransactionRequest) -> Result<TempoTxEnvelope> {
871        if let Some(from) = request.from() {
872            match self.parent {
873                Some(parent) => eyre::ensure!(
874                    from == parent,
875                    "transaction sender {from} is not {parent}, which the configurable access key \
876                     {} signs for",
877                    self.account
878                ),
879                None => eyre::ensure!(
880                    from == self.account,
881                    "transaction sender {from} is not the configurable account {}",
882                    self.account
883                ),
884            }
885        }
886        let tx = request.build_aa().map_err(ca_error)?;
887        let signature = self.sign_hash(tx.signature_hash()).await?;
888        Ok(TempoTxEnvelope::AA(tx.into_signed(signature)))
889    }
890
891    /// Signs `hash`, such as a transaction or zone RPC token digest, with the owners' approvals of
892    /// `configurable_account_digest(hash, account, version)`: a `0x05` signature that recovers the
893    /// account.
894    ///
895    /// As an access key of `parent`, the owners approve the keychain V2 hash
896    /// `keccak256(0x04 || hash || parent)` instead, as Tempo and viem do, and the `0x05` signature
897    /// is wrapped in a keychain signature for `parent`.
898    pub async fn sign_hash(&self, hash: B256) -> Result<TempoSignature> {
899        let inner = match self.parent {
900            Some(parent) => KeychainSignature::signing_hash(hash, parent),
901            None => hash,
902        };
903        let digest = configurable_account_digest(inner, self.account, self.config.version);
904        let mut approvals = Vec::with_capacity(self.owners.len());
905        for owner in &self.owners {
906            approvals.push(owner.sign(&digest).await.wrap_err_with(|| {
907                format!("owner {} failed to approve for {}", owner.address(), self.account)
908            })?);
909        }
910        let signature =
911            ConfigurableAccountSignature::try_new(self.account, self.config.clone(), approvals)
912                .map_err(ca_error)?;
913        signature.verify_approvals(inner).map_err(ca_error)?;
914        Ok(match self.parent {
915            Some(parent) => TempoSignature::Keychain(KeychainSignature::new(parent, signature)),
916            None => TempoSignature::ConfigurableAccount(signature),
917        })
918    }
919}
920
921/// Suffix of the sidecar file that links a keystore to the 1-of-1, salt-0 configurable account
922/// its key owns, next to the keystore as `<keystore>.tempo-account`.
923///
924/// The keystore itself stays a standard Web3 Secret Storage file that other tools read, and the
925/// Tempo Accounts store, whose format belongs to `tempo-alloy`, is not extended.
926pub const LINKED_ACCOUNT_SUFFIX: &str = ".tempo-account";
927
928/// The only linked account sidecar version this release writes and reads.
929const LINKED_ACCOUNT_VERSION: u32 = 1;
930
931/// A keystore's linked account sidecar.
932#[derive(Serialize, Deserialize)]
933#[serde(deny_unknown_fields)]
934struct LinkedAccountFile {
935    version: u32,
936    account: Address,
937    owner: Address,
938}
939
940/// Returns the path of the linked account sidecar of `keystore`.
941pub fn linked_account_path(keystore: &Path) -> PathBuf {
942    let mut path = OsString::from(keystore.as_os_str());
943    path.push(LINKED_ACCOUNT_SUFFIX);
944    path.into()
945}
946
947/// What the file at a linked account sidecar path holds.
948#[derive(Clone, Copy, Debug, PartialEq, Eq)]
949pub enum LinkedAccountFileState {
950    /// There is no file.
951    Missing,
952    /// A link to `account`, the 1-of-1, salt-0 configurable account of `owner`.
953    Linked { account: Address, owner: Address },
954    /// A keystore, such as one an earlier Cast version created under that name.
955    Keystore,
956    /// A file that is neither a link nor a keystore.
957    Unknown,
958}
959
960/// Returns what the file at `path`, a linked account sidecar path, holds.
961pub fn linked_account_file_state(path: &Path) -> Result<LinkedAccountFileState> {
962    let bytes = match std::fs::read(path) {
963        Ok(bytes) => bytes,
964        Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
965            return Ok(LinkedAccountFileState::Missing);
966        }
967        Err(error) => {
968            return Err(error).wrap_err_with(|| format!("failed to read {}", path.display()));
969        }
970    };
971    let Ok(value) = serde_json::from_slice::<Value>(&bytes) else {
972        return Ok(LinkedAccountFileState::Unknown);
973    };
974    if value.get("crypto").is_some() || value.get("Crypto").is_some() {
975        return Ok(LinkedAccountFileState::Keystore);
976    }
977    Ok(match serde_json::from_value::<LinkedAccountFile>(value) {
978        Ok(file)
979            if file.version == LINKED_ACCOUNT_VERSION
980                && single_owner_account(file.owner).ok() == Some(file.account) =>
981        {
982            LinkedAccountFileState::Linked { account: file.account, owner: file.owner }
983        }
984        _ => LinkedAccountFileState::Unknown,
985    })
986}
987
988/// Fails unless the linked account sidecar path of `keystore` is free or holds a link, which
989/// [`link_keystore`] may replace.
990pub fn ensure_link_available(keystore: &Path) -> Result<()> {
991    let path = linked_account_path(keystore);
992    match linked_account_file_state(&path)? {
993        LinkedAccountFileState::Missing | LinkedAccountFileState::Linked { .. } => Ok(()),
994        LinkedAccountFileState::Keystore => eyre::bail!(
995            "refusing to link {} to its configurable account because {} is an existing keystore",
996            keystore.display(),
997            path.display()
998        ),
999        LinkedAccountFileState::Unknown => eyre::bail!(
1000            "refusing to link {} to its configurable account because {} exists and is not a \
1001             recognized linked account file",
1002            keystore.display(),
1003            path.display()
1004        ),
1005    }
1006}
1007
1008/// Links `keystore`, whose key is `owner`, to the 1-of-1, salt-0 configurable account of
1009/// `owner`, and returns that account. Fails when the sidecar path holds another file.
1010pub fn link_keystore(keystore: &Path, owner: Address) -> Result<Address> {
1011    ensure_link_available(keystore)?;
1012    let account = single_owner_account(owner)?;
1013    let file = LinkedAccountFile { version: LINKED_ACCOUNT_VERSION, account, owner };
1014    crate::fs::write_pretty_json_file(&linked_account_path(keystore), &file)?;
1015    Ok(account)
1016}
1017
1018/// Removes the link of `keystore`, and leaves any other file at its sidecar path alone.
1019pub fn unlink_keystore(keystore: &Path) -> Result<()> {
1020    let path = linked_account_path(keystore);
1021    if let LinkedAccountFileState::Linked { .. } = linked_account_file_state(&path)? {
1022        std::fs::remove_file(&path)
1023            .wrap_err_with(|| format!("failed to remove {}", path.display()))?;
1024    }
1025    Ok(())
1026}
1027
1028/// Returns the configurable account linked to `keystore` and its owner key, or `None` when the
1029/// keystore has no link. A keystore at the sidecar path is not a link.
1030pub fn linked_account(keystore: &Path) -> Result<Option<(Address, Address)>> {
1031    let path = linked_account_path(keystore);
1032    match linked_account_file_state(&path)? {
1033        LinkedAccountFileState::Linked { account, owner } => Ok(Some((account, owner))),
1034        LinkedAccountFileState::Missing | LinkedAccountFileState::Keystore => Ok(None),
1035        LinkedAccountFileState::Unknown => eyre::bail!(
1036            "invalid linked account file {}: unsupported version or account",
1037            path.display()
1038        ),
1039    }
1040}
1041
1042#[cfg(test)]
1043mod tests {
1044    use super::*;
1045    use alloy_primitives::{address, b256, keccak256};
1046    use alloy_provider::{ProviderBuilder as AlloyProviderBuilder, mock::Asserter};
1047    use alloy_signer::SignerSync;
1048    use alloy_signer_local::PrivateKeySigner;
1049    use serde_json::json;
1050    use std::str::FromStr;
1051
1052    // Reference values from viem 2.57.17's Tempo account code (`src/tempo/accounts`), computed
1053    // with the `AccountConfig`, `SignatureEnvelope` and `WebAuthnP256` modules of the `ox` 0.14.63
1054    // it pins. The secp256k1 owner is the key `0x11..11`; the passkey owner is the P-256 key
1055    // `0x22..22`, and its assertion of `DIGEST_V0` uses the RP ID and origin `example.com`.
1056    const OWNER: Address = address!("0x19e7e376e7c213b7e7e7e46cc70a5dd086daff2a");
1057    const ACCOUNT: Address = address!("0x75f3c248135efae1fc77cf590d925e227e8679a4");
1058    const COMMITMENT: B256 =
1059        b256!("0x403996416648fe4366d9d8fb0990eadc5a54b9e1c4f7ab43f8450c41281ac7c3");
1060    /// `getSignPayload` of the inner digest `0xab..ab` for `ACCOUNT` at versions zero and three.
1061    const DIGEST_V0: B256 =
1062        b256!("0x06d4fcd0bd0743b539be1a3538f890822c2e515b3b6a6df0f0e7f113c0bd5494");
1063    const DIGEST_V3: B256 =
1064        b256!("0x2280b991255d42ee809294d82f8677350f413b4115fb63adaaa1a69a0c99eb0d");
1065    const PASSKEY_OWNER: Address = address!("0x61c835c32c4bd8f60da77d577e4dfdc2dd5b6f9b");
1066    const WEBAUTHN_ENVELOPE: &str = "0x02a379a6f6eeafb9a55e378c118034e2751e682fab9f2d30ab13d2125586ce194705000000007b2274797065223a22776562617574686e2e676574222c226368616c6c656e6765223a2242745438304c30485137553576686f314f5069516769777555567337616d3377384f667845384339564a51222c226f726967696e223a2268747470733a2f2f6578616d706c652e636f6d222c2263726f73734f726967696e223a66616c73657df1ea2f854bb598362f723afa3db60f872dc3b8739110be94955ab231274e48c815ad66f22ca81b6a5bb17f27ee2e37d7dbf867c76135b864e9e1b97e04bc6bb1d65a93977caa3d1b081852ff57a79e465f1660577304baead505dd3a48589cf350185e895372df6221ea3a137557e473fddb6755f05bd507c3c533fce9c91285";
1067
1068    #[test]
1069    fn single_owner_account_matches_viem() {
1070        let owner = PrivateKeySigner::from_bytes(&B256::repeat_byte(0x11)).unwrap().address();
1071        assert_eq!(owner, OWNER);
1072        assert_eq!(single_owner_account(owner).unwrap(), ACCOUNT);
1073        assert_eq!(single_owner_config(owner).commitment().unwrap(), COMMITMENT);
1074        let inner = B256::repeat_byte(0xab);
1075        assert_eq!(configurable_account_digest(inner, ACCOUNT, 0), DIGEST_V0);
1076        assert_eq!(configurable_account_digest(inner, ACCOUNT, 3), DIGEST_V3);
1077    }
1078
1079    /// A browser assertion parses to the envelope `ox` serializes for it, with its high-s
1080    /// signature normalized, and recovers the passkey owner.
1081    #[test]
1082    fn webauthn_assertion_matches_viem_envelope() {
1083        let envelope = parse_owner_signature(WEBAUTHN_ENVELOPE).unwrap();
1084        assert_eq!(envelope.recover_signer(&DIGEST_V0).unwrap(), PASSKEY_OWNER);
1085
1086        let r = "f1ea2f854bb598362f723afa3db60f872dc3b8739110be94955ab231274e48c8";
1087        let s =
1088            U256::from_str("0x15ad66f22ca81b6a5bb17f27ee2e37d7dbf867c76135b864e9e1b97e04bc6bb1")
1089                .unwrap();
1090        let order =
1091            U256::from_str("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551")
1092                .unwrap();
1093        let high_s = order - s;
1094        let signature = p256::ecdsa::Signature::from_scalars(
1095            B256::from_str(r).unwrap().0,
1096            B256::from(high_s).0,
1097        )
1098        .unwrap();
1099        let x = "d65a93977caa3d1b081852ff57a79e465f1660577304baead505dd3a48589cf3";
1100        let y = "50185e895372df6221ea3a137557e473fddb6755f05bd507c3c533fce9c91285";
1101        let client_data = r#"{"type":"webauthn.get","challenge":"BtT80L0HQ7U5vho1OPiQgiwuUVs7am3w8OfxE8C9VJQ","origin":"https://example.com","crossOrigin":false}"#;
1102        let engine = base64::engine::general_purpose::URL_SAFE_NO_PAD;
1103        let assertion = json!({
1104            "id": "credential",
1105            "type": "public-key",
1106            "response": {
1107                "authenticatorData": engine.encode(
1108                    hex::decode("a379a6f6eeafb9a55e378c118034e2751e682fab9f2d30ab13d2125586ce19470500000000")
1109                        .unwrap()
1110                ),
1111                "clientDataJSON": engine.encode(client_data),
1112                "signature": engine.encode(signature.to_der()),
1113            },
1114            "publicKey": format!("0x04{x}{y}"),
1115        });
1116        let parsed = parse_owner_signature(&assertion.to_string()).unwrap();
1117        assert_eq!(parsed, envelope);
1118    }
1119
1120    /// A raw `r || s` signature whose `r` starts with the DER sequence tag `0x30` parses as raw.
1121    #[test]
1122    fn webauthn_assertion_accepts_raw_signature_starting_with_der_tag() {
1123        let (r, s) = (B256::repeat_byte(0x30), B256::repeat_byte(0x01));
1124        let assertion = json!({
1125            "authenticatorData": "0x00",
1126            "clientDataJSON": "{}",
1127            "signature": hex::encode_prefixed([r.as_slice(), s.as_slice()].concat()),
1128            "publicKey": format!("0x04{}", "11".repeat(64)),
1129        });
1130        let PrimitiveSignature::WebAuthn(signature) =
1131            parse_owner_signature(&assertion.to_string()).unwrap()
1132        else {
1133            panic!("expected a WebAuthn signature");
1134        };
1135        assert_eq!((signature.r, signature.s), (r, s));
1136    }
1137
1138    /// P-256 approvals cover the digest itself and stay low-s, which Tempo's verifier requires
1139    /// and about half of raw ECDSA signatures are not.
1140    #[test]
1141    fn p256_approvals_recover_the_owner() {
1142        let key = p256::ecdsa::SigningKey::from_slice(&[0x22; 32]).unwrap();
1143        for byte in 0..16 {
1144            let digest = keccak256([byte]);
1145            let signature = sign_p256(&key, &digest).unwrap();
1146            assert!(matches!(&signature, PrimitiveSignature::P256(p256) if !p256.pre_hash));
1147            assert_eq!(signature.recover_signer(&digest).unwrap(), PASSKEY_OWNER);
1148        }
1149        assert!(parse_p256_key("0x1234").is_err());
1150        assert!(parse_p256_key(&format!("0x{}", "22".repeat(32))).is_ok());
1151    }
1152
1153    /// The worst-case quorum is the largest one the node accepts: in address order it reaches the
1154    /// threshold only on its last approval, and it holds at most eight approvals.
1155    #[test]
1156    fn worst_case_quorum_reaches_threshold_on_last_approval() {
1157        let quorum = |threshold, weights: &[(u8, u8)]| {
1158            let config = ConfigurableAccountConfig {
1159                salt: B256::ZERO,
1160                version: 1,
1161                threshold,
1162                owners: weights
1163                    .iter()
1164                    .map(|&(byte, weight)| ConfigurableAccountOwner {
1165                        owner: Address::repeat_byte(byte),
1166                        weight,
1167                    })
1168                    .collect(),
1169            };
1170            config.validate().unwrap();
1171            simulation_spec(Address::repeat_byte(0xaa), &config, &[])
1172                .approvals
1173                .into_iter()
1174                .map(|approval| approval.owner.0[0])
1175                .collect::<Vec<_>>()
1176        };
1177
1178        // The three lightest owners overshoot: 0x11 and 0x22 already reach 5.
1179        assert_eq!(quorum(5, &[(0x11, 4), (0x22, 2), (0x33, 2)]), [0x11, 0x22]);
1180        // The heaviest owner sorts first, so it can only approve alone.
1181        let mut owners = vec![(0x01, 10)];
1182        owners.extend((0x10..0x19).map(|byte| (byte, 1)));
1183        assert_eq!(quorum(10, &owners), [0x01]);
1184        // The lightest owners would need ten approvals; eight is the most the node accepts.
1185        let mut owners = (0x10..0x1a).map(|byte| (byte, 1)).collect::<Vec<_>>();
1186        owners.push((0xff, 10));
1187        assert_eq!(quorum(10, &owners), [0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0xff]);
1188    }
1189
1190    /// Assembly keeps the fewest supplied approvals that the node accepts, even when all of them
1191    /// together exceed the eight-signature limit.
1192    #[test]
1193    fn combine_approvals_selects_a_quorum_within_the_signature_limit() {
1194        let keys = (1..=9u8)
1195            .map(|byte| PrivateKeySigner::from_bytes(&B256::repeat_byte(byte)).unwrap())
1196            .collect::<Vec<_>>();
1197        let mut owners = keys
1198            .iter()
1199            .map(|key| ConfigurableAccountOwner { owner: key.address(), weight: 1 })
1200            .collect::<Vec<_>>();
1201        owners.sort_by_key(|owner| owner.owner);
1202        // The heaviest owner sorts last.
1203        let heavy = owners.last().unwrap().owner;
1204        owners.last_mut().unwrap().weight = 9;
1205        let config =
1206            ConfigurableAccountConfig { salt: B256::ZERO, version: 1, threshold: 9, owners };
1207        let (account, inner) = (Address::repeat_byte(0xaa), B256::repeat_byte(0xab));
1208        let digest = configurable_account_digest(inner, account, config.version);
1209        let approvals = keys
1210            .iter()
1211            .map(|key| PrimitiveSignature::Secp256k1(key.sign_hash_sync(&digest).unwrap()))
1212            .collect();
1213
1214        let signature = combine_approvals(account, &config, inner, approvals).unwrap();
1215        assert_eq!(signature.signatures().len(), 1);
1216        assert_eq!(signature.signatures()[0].recover_signer(&digest).unwrap(), heavy);
1217    }
1218
1219    /// The lookup halves its block window when the RPC rejects a range, walks back past windows
1220    /// without events, and takes the latest event of the window that has one.
1221    #[tokio::test]
1222    async fn config_lookup_shrinks_rejected_ranges_and_takes_latest_event() {
1223        let account = Address::repeat_byte(0xaa);
1224        let config = |version, threshold| ConfigurableAccountConfig {
1225            salt: B256::repeat_byte(0x5a),
1226            version,
1227            threshold,
1228            owners: vec![
1229                ConfigurableAccountOwner { owner: Address::repeat_byte(0x11), weight: 1 },
1230                ConfigurableAccountOwner { owner: Address::repeat_byte(0x22), weight: 1 },
1231            ],
1232        };
1233        let log = |config: &ConfigurableAccountConfig| Log {
1234            inner: alloy_primitives::Log {
1235                address: CONFIGURABLE_ACCOUNT_ADDRESS,
1236                data: ConfigurableAccountConfigUpdated {
1237                    account,
1238                    salt: config.salt,
1239                    version: config.version,
1240                    threshold: config.threshold,
1241                    owners: abi_owners(config),
1242                }
1243                .encode_log_data(),
1244            },
1245            ..Default::default()
1246        };
1247        let (old, current) = (config(1, 2), config(2, 1));
1248
1249        let asserter = Asserter::new();
1250        // Blocks 150_001..=250_000 exceed the RPC's range limit, 200_001..=250_000 have no events,
1251        // and 150_001..=200_000 hold an older event followed by the current one.
1252        asserter.push_failure_msg("query exceeds max block range");
1253        asserter.push_success(&Vec::<Log>::new());
1254        asserter.push_success(&vec![log(&old), log(&current)]);
1255        let provider =
1256            AlloyProviderBuilder::new().network::<TempoNetwork>().connect_mocked_client(asserter);
1257
1258        let found = config_from_logs(&provider, account, current.commitment().unwrap(), 250_000)
1259            .await
1260            .unwrap();
1261        assert_eq!(found, current);
1262
1263        // An event that does not match the onchain commitment is rejected.
1264        let asserter = Asserter::new();
1265        asserter.push_success(&vec![log(&old)]);
1266        let provider =
1267            AlloyProviderBuilder::new().network::<TempoNetwork>().connect_mocked_client(asserter);
1268        let err = config_from_logs(&provider, account, current.commitment().unwrap(), 10)
1269            .await
1270            .unwrap_err();
1271        assert!(err.to_string().contains("does not match its commitment"), "{err}");
1272    }
1273
1274    /// The signer takes the fewest local owners that reach the threshold, sorted by address,
1275    /// ignores keys that are not owners, and its signature passes the node's quorum check, which
1276    /// rejects unsorted or excess approvals.
1277    #[tokio::test]
1278    async fn signer_selects_sorted_owners_up_to_the_threshold() {
1279        let mut keys = [0x51, 0x52, 0x53, 0x54]
1280            .map(|byte| PrivateKeySigner::from_bytes(&B256::repeat_byte(byte)).unwrap());
1281        keys.sort_by_key(|key| key.address());
1282        let [low, mid, high, stranger] = keys.clone();
1283        // The middle owner weighs two and reaches the threshold of two alone, so the lowest owner,
1284        // which comes first in address order, is left out.
1285        let mut owners = [(&low, 1), (&mid, 2), (&high, 1)]
1286            .map(|(key, weight)| ConfigurableAccountOwner { owner: key.address(), weight })
1287            .to_vec();
1288        owners.sort_by_key(|owner| owner.owner);
1289        let config = ConfigurableAccountConfig {
1290            salt: B256::repeat_byte(1),
1291            version: 0,
1292            threshold: 2,
1293            owners,
1294        };
1295        let account = config.derive_account().unwrap();
1296
1297        let wallet = |key: &PrivateKeySigner| {
1298            ConfigurableAccountOwnerKey::from(WalletSigner::Local(key.clone()))
1299        };
1300        let signer = ConfigurableAccountSigner::new(
1301            account,
1302            config.clone(),
1303            [&stranger, &high, &mid, &low].map(wallet),
1304            "",
1305        )
1306        .unwrap();
1307        let spec = signer.simulation_spec();
1308        assert_eq!(
1309            spec.approvals.iter().map(|approval| approval.owner).collect::<Vec<_>>(),
1310            [mid.address()]
1311        );
1312        assert!(
1313            spec.approvals
1314                .iter()
1315                .all(|approval| approval.key_type == Some(PrimitiveSignatureType::Secp256k1))
1316        );
1317
1318        let mut request = TempoTransactionRequest::default();
1319        request.set_from(account);
1320        request.set_chain_id(1);
1321        request.set_nonce(0);
1322        request.set_gas_limit(100_000);
1323        request.set_max_fee_per_gas(2);
1324        request.set_max_priority_fee_per_gas(1);
1325        request.set_to(Address::repeat_byte(0x73));
1326        let TempoTxEnvelope::AA(signed) = signer.sign_request(request).await.unwrap() else {
1327            panic!("expected a Tempo transaction");
1328        };
1329        let signature = signed.signature().as_configurable_account().unwrap();
1330        assert_eq!(signature.signatures().len(), 1);
1331        signature.verify_approvals(signed.tx().signature_hash()).unwrap();
1332
1333        // The highest owner alone does not reach the threshold.
1334        let err = ConfigurableAccountSigner::new(account, config, [wallet(&high)], "Pass more.")
1335            .unwrap_err()
1336            .to_string();
1337        assert_eq!(
1338            err,
1339            format!(
1340                "{account} is a Tempo configurable account that needs owner weight 2, but the \
1341                 local owner keys {} reach weight 1. Its owners are {} (weight 1), {} (weight 2), \
1342                 {} (weight 1). Pass more.",
1343                high.address(),
1344                low.address(),
1345                mid.address(),
1346                high.address()
1347            )
1348        );
1349    }
1350
1351    /// With eight weight-one owners and a weight-nine owner last in address order, the signer
1352    /// takes the heavy owner alone: the first owners in address order would need nine approvals,
1353    /// over the node's limit of eight.
1354    #[test]
1355    fn signer_selects_a_quorum_within_the_signature_limit() {
1356        let keys = (1..=9u8)
1357            .map(|byte| PrivateKeySigner::from_bytes(&B256::repeat_byte(byte)).unwrap())
1358            .collect::<Vec<_>>();
1359        let mut owners = keys
1360            .iter()
1361            .map(|key| ConfigurableAccountOwner { owner: key.address(), weight: 1 })
1362            .collect::<Vec<_>>();
1363        owners.sort_by_key(|owner| owner.owner);
1364        let heavy = owners.last().unwrap().owner;
1365        owners.last_mut().unwrap().weight = 9;
1366        let config =
1367            ConfigurableAccountConfig { salt: B256::ZERO, version: 1, threshold: 9, owners };
1368        let account = Address::repeat_byte(0xaa);
1369        let wallet = |key: &PrivateKeySigner| {
1370            ConfigurableAccountOwnerKey::from(WalletSigner::Local(key.clone()))
1371        };
1372
1373        let addresses = keys.iter().map(|key| key.address()).collect::<Vec<_>>();
1374        assert!(reaches_threshold(&config, &addresses));
1375        let signer =
1376            ConfigurableAccountSigner::new(account, config.clone(), keys.iter().map(wallet), "")
1377                .unwrap();
1378        assert_eq!(
1379            signer.simulation_spec().approvals.iter().map(|a| a.owner).collect::<Vec<_>>(),
1380            [heavy]
1381        );
1382
1383        // Nine weight-one owners reach the threshold of nine only past the limit, so `forge
1384        // script` saves their transactions for offline owners.
1385        let mut config = config;
1386        config.owners.last_mut().unwrap().weight = 1;
1387        assert!(!reaches_threshold(&config, &addresses));
1388        let owners = config.owners.iter().map(|owner| owner.owner.to_string()).collect::<Vec<_>>();
1389        let err = ConfigurableAccountSigner::new(
1390            account,
1391            config.clone(),
1392            keys.iter().map(wallet),
1393            "Pass more.",
1394        )
1395        .unwrap_err()
1396        .to_string();
1397        assert_eq!(
1398            err,
1399            format!(
1400                "{account} is a Tempo configurable account that needs owner weight 9, but no 8 of \
1401                 the local owner keys {} reach it. Its owners are {}. Pass more.",
1402                owners.join(", "),
1403                owners
1404                    .iter()
1405                    .map(|owner| format!("{owner} (weight 1)"))
1406                    .collect::<Vec<_>>()
1407                    .join(", ")
1408            )
1409        );
1410    }
1411
1412    #[test]
1413    fn parses_config_json_with_or_without_envelope() {
1414        let config = ConfigurableAccountConfig {
1415            salt: B256::repeat_byte(2),
1416            version: 3,
1417            threshold: 2,
1418            owners: vec![
1419                ConfigurableAccountOwner { owner: Address::repeat_byte(0x11), weight: 1 },
1420                ConfigurableAccountOwner { owner: Address::repeat_byte(0x22), weight: 1 },
1421            ],
1422        };
1423        let data = serde_json::json!({
1424            "account": Address::repeat_byte(0xaa),
1425            "version": 3,
1426            "threshold": 2,
1427            "salt": B256::repeat_byte(2),
1428            "commitment": config.commitment().unwrap(),
1429            // Unsorted owners are sorted.
1430            "owners": [
1431                { "owner": Address::repeat_byte(0x22), "weight": 1 },
1432                { "owner": Address::repeat_byte(0x11), "weight": 1 },
1433            ],
1434        });
1435        assert_eq!(parse_config(&data.to_string()).unwrap(), config);
1436        let envelope = serde_json::json!({ "success": true, "data": data });
1437        assert_eq!(parse_config(&envelope.to_string()).unwrap(), config);
1438        // A threshold above the total weight is rejected.
1439        let mut invalid = data;
1440        invalid["threshold"] = 3.into();
1441        assert!(parse_config(&invalid.to_string()).is_err());
1442    }
1443
1444    #[test]
1445    fn link_leaves_a_keystore_with_the_sidecar_name_alone() {
1446        let dir = tempfile::tempdir().unwrap();
1447        let keystore = dir.path().join("dev");
1448        let owner = Address::repeat_byte(0x31);
1449        let account = single_owner_account(owner).unwrap();
1450
1451        // A link is written, read, replaced and removed.
1452        assert_eq!(linked_account(&keystore).unwrap(), None);
1453        assert_eq!(link_keystore(&keystore, owner).unwrap(), account);
1454        assert_eq!(linked_account(&keystore).unwrap(), Some((account, owner)));
1455        link_keystore(&keystore, owner).unwrap();
1456        unlink_keystore(&keystore).unwrap();
1457        assert!(!linked_account_path(&keystore).exists());
1458
1459        // An earlier Cast version could create a keystore named `dev.tempo-account`.
1460        let other = r#"{"version":3,"id":"x","crypto":{"cipher":"aes-128-ctr"}}"#;
1461        std::fs::write(linked_account_path(&keystore), other).unwrap();
1462        assert_eq!(linked_account(&keystore).unwrap(), None);
1463        assert!(link_keystore(&keystore, owner).is_err());
1464        unlink_keystore(&keystore).unwrap();
1465        assert_eq!(std::fs::read_to_string(linked_account_path(&keystore)).unwrap(), other);
1466
1467        // Any other file is neither replaced nor removed, and is not taken as a link.
1468        std::fs::write(linked_account_path(&keystore), "notes").unwrap();
1469        assert!(ensure_link_available(&keystore).is_err());
1470        assert!(linked_account(&keystore).is_err());
1471        unlink_keystore(&keystore).unwrap();
1472        assert_eq!(std::fs::read_to_string(linked_account_path(&keystore)).unwrap(), "notes");
1473    }
1474}