Skip to main content

foundry_common/tempo/
keystore.rs

1//! Tempo Accounts store discovery and local key metadata.
2
3use alloy_primitives::{Address, hex};
4use alloy_rlp::Decodable;
5use serde::{Deserialize, Serialize};
6use std::path::PathBuf;
7use tempo_alloy::accounts::{TempoAccountsStore, default_accounts_store_path};
8use tempo_primitives::{
9    SignatureType,
10    transaction::{SignedKeyAuthorization, TokenLimit},
11};
12
13/// Environment variable to override the Tempo home directory.
14pub const TEMPO_HOME_ENV: &str = "TEMPO_HOME";
15
16/// Cryptographic key type used by Tempo Accounts access keys.
17#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize, Serialize)]
18#[serde(rename_all = "lowercase")]
19pub enum KeyType {
20    #[default]
21    Secp256k1,
22    P256,
23    WebAuthn,
24    /// A configurable account (owner quorum) acting as an access key, from T14.
25    ConfigurableAccount,
26}
27
28impl From<SignatureType> for KeyType {
29    fn from(value: SignatureType) -> Self {
30        match value {
31            SignatureType::Secp256k1 => Self::Secp256k1,
32            SignatureType::P256 => Self::P256,
33            SignatureType::WebAuthn => Self::WebAuthn,
34            SignatureType::ConfigurableAccount => Self::ConfigurableAccount,
35        }
36    }
37}
38
39/// Per-token spending limit exposed by the local keychain commands.
40#[derive(Debug, Clone)]
41pub struct StoredTokenLimit {
42    pub currency: Address,
43    pub limit: String,
44    pub period: u64,
45}
46
47impl From<&TokenLimit> for StoredTokenLimit {
48    fn from(value: &TokenLimit) -> Self {
49        Self { currency: value.token, limit: value.limit.to_string(), period: value.period }
50    }
51}
52
53/// Non-secret view of one access key in the Tempo Accounts store.
54#[derive(Clone, Default)]
55pub struct KeyEntry {
56    pub wallet_address: Address,
57    pub chain_id: u64,
58    pub key_type: KeyType,
59    pub key_address: Address,
60    pub key_authorization: Option<SignedKeyAuthorization>,
61    pub expiry: Option<u64>,
62    pub limits: Vec<StoredTokenLimit>,
63    locally_signable: bool,
64}
65
66impl std::fmt::Debug for KeyEntry {
67    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
68        f.debug_struct("KeyEntry")
69            .field("wallet_address", &self.wallet_address)
70            .field("chain_id", &self.chain_id)
71            .field("key_type", &self.key_type)
72            .field("key_address", &self.key_address)
73            .field("has_key", &self.locally_signable)
74            .field("has_key_authorization", &self.key_authorization.is_some())
75            .field("expiry", &self.expiry)
76            .field("limits", &self.limits)
77            .finish()
78    }
79}
80
81impl KeyEntry {
82    /// Construct non-secret metadata for one Tempo Accounts access key.
83    pub const fn new(
84        wallet_address: Address,
85        chain_id: u64,
86        key_type: KeyType,
87        key_address: Address,
88    ) -> Self {
89        Self {
90            wallet_address,
91            chain_id,
92            key_type,
93            key_address,
94            key_authorization: None,
95            expiry: None,
96            limits: Vec::new(),
97            locally_signable: false,
98        }
99    }
100
101    /// Attach a pending authorization to this metadata view.
102    #[doc(hidden)]
103    pub fn with_key_authorization(mut self, authorization: SignedKeyAuthorization) -> Self {
104        self.key_authorization = Some(authorization);
105        self
106    }
107
108    /// Whether the Accounts store contains usable local signing material.
109    pub const fn has_inline_key(&self) -> bool {
110        self.locally_signable
111    }
112
113    /// Override local signing availability when constructing diagnostic fixtures.
114    #[doc(hidden)]
115    pub const fn with_locally_signable(mut self, locally_signable: bool) -> Self {
116        self.locally_signable = locally_signable;
117        self
118    }
119}
120
121/// Snapshot used by the existing keychain list/show/doctor commands.
122#[derive(Debug, Default)]
123pub struct AccountsStoreView {
124    pub keys: Vec<KeyEntry>,
125}
126
127/// Return the canonical Tempo Accounts `store.json` path.
128pub fn tempo_accounts_store_path() -> Option<PathBuf> {
129    default_accounts_store_path().ok()
130}
131
132/// Read non-secret metadata from the canonical Tempo Accounts store.
133pub fn read_tempo_accounts_store() -> Option<AccountsStoreView> {
134    let store = match TempoAccountsStore::try_open_default() {
135        Ok(Some(store)) => store,
136        Ok(None) => return None,
137        Err(error) => {
138            tracing::warn!(%error, "failed to open Tempo Accounts store");
139            return None;
140        }
141    };
142    let keys = match store.access_keys() {
143        Ok(keys) => keys,
144        Err(error) => {
145            tracing::warn!(%error, path = %store.path().display(), "failed to read Tempo Accounts access keys");
146            return None;
147        }
148    };
149    Some(AccountsStoreView {
150        keys: keys
151            .into_iter()
152            .map(|key| KeyEntry {
153                wallet_address: key.account(),
154                chain_id: key.chain_id(),
155                key_type: key.key_type().into(),
156                key_address: key.address(),
157                key_authorization: key.key_authorization().cloned(),
158                expiry: key.expiry(),
159                limits: key.limits().iter().map(Into::into).collect(),
160                locally_signable: key.is_locally_signable(),
161            })
162            .collect(),
163    })
164}
165
166/// Decode an RLP key authorization stored by Tempo Accounts.
167pub fn decode_key_authorization<T: Decodable>(encoded: &str) -> eyre::Result<T> {
168    let bytes = hex::decode(encoded)?;
169    let mut bytes = bytes.as_slice();
170    let authorization = T::decode(&mut bytes)?;
171    if !bytes.is_empty() {
172        eyre::bail!("key authorization has trailing bytes");
173    }
174    Ok(authorization)
175}