Skip to main content

beekeeper/
wallet.rs

1//! Locked / unlocked wallet handles.
2//!
3//! Lock state is encoded in the type system: [`LockedWallet`] and
4//! [`UnlockedWallet`] are distinct types, and every transition
5//! (`unlock` / `lock` / `close`) consumes its receiver and returns the next
6//! state. Calling a key operation on a locked wallet is a compile error,
7//! not a runtime check.
8
9use std::{
10    cell::{RefCell, RefMut},
11    ops::{Deref, DerefMut},
12    rc::Rc,
13};
14
15use crate::{api::Inner, errors::BeekeeperError};
16
17/// Address-format prefix used for every Hive public key serialised by the
18/// C++ side ("STM…").
19pub const DEFAULT_KEY_PREFIX: &str = "STM";
20
21/// Plain summary of a wallet returned from listing operations.
22///
23/// Combines the C++ holder's `(name, unlocked)` data with the Rust-tracked
24/// `is_temporary` flag.
25pub struct WalletInfo {
26    pub name: String,
27    pub unlocked: bool,
28    pub is_temporary: bool,
29}
30
31/// Result of [`Session::create_wallet`](crate::session::Session::create_wallet).
32///
33/// `password` is whichever password ended up protecting the wallet — either
34/// the caller-supplied value, or the generated one when `None` was passed.
35///
36/// Dereferences to the contained [`UnlockedWallet`], so key operations can
37/// be called on it directly:
38///
39/// ```no_run
40/// # use beekeeper::prelude::*;
41/// # let bk = BeekeeperApi::new(None);
42/// # let session = bk.create_session().unwrap();
43/// let mut created = session.create_wallet("w0", "password").unwrap();
44/// let pubkey = created.import_key("5J...wif...").unwrap();
45/// ```
46pub struct CreatedWallet {
47    pub wallet: UnlockedWallet,
48    pub password: String,
49}
50
51/// A wallet known to the wallet manager but currently locked.
52///
53/// Shares the underlying state with the parent
54/// [`Session`](crate::session::Session) — the handle stays valid for as
55/// long as the session is alive.
56pub struct LockedWallet {
57    handle: WalletHandle,
58}
59
60/// A wallet that is currently unlocked and ready to perform key operations.
61///
62/// Every operation first checks the inactivity timeout, so calls issued
63/// after it elapsed fail with [`BeekeeperError::TimedOut`] instead of
64/// silently succeeding.
65pub struct UnlockedWallet {
66    handle: WalletHandle,
67}
68
69/// State common to both lock states: the wallet's identity plus access to
70/// the beekeeper it belongs to. Transitions move the handle unchanged.
71struct WalletHandle {
72    inner: Rc<RefCell<Inner>>,
73    name: String,
74    is_temporary: bool,
75}
76
77impl CreatedWallet {
78    /// Consume the pair, keeping only the wallet handle.
79    pub fn into_wallet(self) -> UnlockedWallet {
80        self.wallet
81    }
82
83    /// Forward of [`UnlockedWallet::lock`] (consuming methods cannot go
84    /// through `Deref`).
85    pub fn lock(self) -> Result<LockedWallet, BeekeeperError> {
86        self.wallet.lock()
87    }
88
89    /// Forward of [`UnlockedWallet::close`].
90    pub fn close(self) -> Result<(), BeekeeperError> {
91        self.wallet.close()
92    }
93}
94
95impl Deref for CreatedWallet {
96    type Target = UnlockedWallet;
97
98    fn deref(&self) -> &UnlockedWallet {
99        &self.wallet
100    }
101}
102
103impl DerefMut for CreatedWallet {
104    fn deref_mut(&mut self) -> &mut UnlockedWallet {
105        &mut self.wallet
106    }
107}
108
109impl LockedWallet {
110    pub(crate) fn new(
111        inner: Rc<RefCell<Inner>>,
112        name: String,
113        is_temporary: bool,
114    ) -> Self {
115        Self {
116            handle: WalletHandle::new(inner, name, is_temporary),
117        }
118    }
119
120    /// The wallet's name, as passed to `create_wallet` / `open_wallet`.
121    pub fn name(&self) -> &str {
122        &self.handle.name
123    }
124
125    /// `true` when the wallet lives only in process memory and is never
126    /// persisted.
127    pub fn is_temporary(&self) -> bool {
128        self.handle.is_temporary
129    }
130
131    /// Unlock with the given password.
132    ///
133    /// Consumes `self` and returns an [`UnlockedWallet`]. Also refreshes
134    /// the activity clock so the freshly-unlocked wallet has a full
135    /// timeout window before any operation runs.
136    pub fn unlock(
137        self,
138        password: &str,
139    ) -> Result<UnlockedWallet, BeekeeperError> {
140        {
141            let mut inner = self.handle.inner.borrow_mut();
142            inner.holder.pin_mut().unlock(&self.handle.name, password)?;
143            inner.refresh_timeout();
144        }
145
146        Ok(UnlockedWallet {
147            handle: self.handle,
148        })
149    }
150
151    /// Close the wallet on the C++ side.
152    ///
153    /// Consumes `self`. The Rust-side metadata entry stays put — close the
154    /// session if you want it gone, or call
155    /// [`Session::close_wallet`](crate::session::Session::close_wallet)
156    /// instead, which also unregisters the metadata.
157    pub fn close(self) -> Result<(), BeekeeperError> {
158        let mut inner = self.handle.inner.borrow_mut();
159        inner.holder.pin_mut().close_wallet(&self.handle.name)?;
160
161        Ok(())
162    }
163}
164
165impl UnlockedWallet {
166    pub(crate) fn new(
167        inner: Rc<RefCell<Inner>>,
168        name: String,
169        is_temporary: bool,
170    ) -> Self {
171        Self {
172            handle: WalletHandle::new(inner, name, is_temporary),
173        }
174    }
175
176    /// The wallet's name, as passed to `create_wallet` / `open_wallet`.
177    pub fn name(&self) -> &str {
178        &self.handle.name
179    }
180
181    /// `true` when the wallet lives only in process memory and is never
182    /// persisted.
183    pub fn is_temporary(&self) -> bool {
184        self.handle.is_temporary
185    }
186
187    /// Lock the wallet and return its [`LockedWallet`] form.
188    ///
189    /// Does **not** check the inactivity timeout — locking is always
190    /// allowed, even (especially) if the wallet has already auto-locked
191    /// underneath us.
192    pub fn lock(self) -> Result<LockedWallet, BeekeeperError> {
193        {
194            let mut inner = self.handle.inner.borrow_mut();
195            inner.holder.pin_mut().lock(&self.handle.name)?;
196        }
197
198        Ok(LockedWallet {
199            handle: self.handle,
200        })
201    }
202
203    /// Lock then close the wallet.
204    pub fn close(self) -> Result<(), BeekeeperError> {
205        let locked = self.lock()?;
206        locked.close()
207    }
208
209    /// Import a WIF-encoded private key and return its public counterpart.
210    ///
211    /// The returned key is base58 with the [`DEFAULT_KEY_PREFIX`] prefix
212    /// (e.g. `"STM7..."`).
213    pub fn import_key(
214        &mut self,
215        wif_key: &str,
216    ) -> Result<String, BeekeeperError> {
217        let mut inner = self.handle.refreshed()?;
218        let public_key = inner.holder.pin_mut().import_key(
219            &self.handle.name,
220            wif_key,
221            DEFAULT_KEY_PREFIX,
222        )?;
223
224        Ok(public_key)
225    }
226
227    /// Remove the private key matching `public_key` (`STM…`).
228    ///
229    /// Errors when no such key exists in the wallet.
230    pub fn remove_key(
231        &mut self,
232        public_key: &str,
233    ) -> Result<(), BeekeeperError> {
234        let mut inner = self.handle.refreshed()?;
235        inner.holder.pin_mut().remove_key(
236            &self.handle.name,
237            public_key,
238            DEFAULT_KEY_PREFIX,
239        )?;
240
241        Ok(())
242    }
243
244    /// `true` when the wallet contains the private key for `public_key`.
245    pub fn has_matching_private_key(
246        &mut self,
247        public_key: &str,
248    ) -> Result<bool, BeekeeperError> {
249        let inner = self.handle.refreshed()?;
250        let has_key = inner.holder.has_matching_private_key(
251            &self.handle.name,
252            public_key,
253            DEFAULT_KEY_PREFIX,
254        )?;
255
256        Ok(has_key)
257    }
258
259    /// Sign a pre-computed digest with the private key matching `public_key`.
260    ///
261    /// `digest_hex` must be the hex encoding of a 32-byte digest. The
262    /// returned signature is the hex encoding of the 65-byte compact
263    /// signature.
264    pub fn sign_digest(
265        &mut self,
266        public_key: &str,
267        digest_hex: &str,
268    ) -> Result<String, BeekeeperError> {
269        let mut inner = self.handle.refreshed()?;
270        let signature = inner.holder.pin_mut().sign_digest(
271            &self.handle.name,
272            digest_hex,
273            public_key,
274            DEFAULT_KEY_PREFIX,
275        )?;
276
277        Ok(signature)
278    }
279
280    /// Every public key held by the wallet, formatted with
281    /// [`DEFAULT_KEY_PREFIX`].
282    pub fn get_public_keys(&mut self) -> Result<Vec<String>, BeekeeperError> {
283        let inner = self.handle.refreshed()?;
284        let keys = inner
285            .holder
286            .get_public_keys(&self.handle.name, DEFAULT_KEY_PREFIX)?;
287
288        Ok(keys)
289    }
290
291    /// Encrypt `content` between two keys, returning a base58 buffer.
292    ///
293    /// `from_key` must be present in the wallet (its private key is used
294    /// for the ECDH side). `to_key` accepts anything convertible into
295    /// `Option<&str>`; `None` is interpreted as self-encryption
296    /// (`to_key = from_key`).
297    ///
298    /// `nonce` is mixed into the encryption to make output reproducible;
299    /// pass `0` to have the C++ side generate a random nonce instead.
300    pub fn encrypt_data<'k>(
301        &mut self,
302        from_key: &str,
303        to_key: impl Into<Option<&'k str>>,
304        content: &str,
305        nonce: u64,
306    ) -> Result<String, BeekeeperError> {
307        let to_key = to_key.into().unwrap_or(from_key);
308        let mut inner = self.handle.refreshed()?;
309        let encrypted = inner.holder.pin_mut().encrypt_data(
310            &self.handle.name,
311            from_key,
312            to_key,
313            content,
314            DEFAULT_KEY_PREFIX,
315            nonce,
316        )?;
317
318        Ok(encrypted)
319    }
320
321    /// Decrypt a base58 buffer produced by [`encrypt_data`](Self::encrypt_data).
322    ///
323    /// `to_key = None` defaults to `from_key`, mirroring the encrypt side.
324    pub fn decrypt_data<'k>(
325        &mut self,
326        from_key: &str,
327        to_key: impl Into<Option<&'k str>>,
328        encrypted_content: &str,
329    ) -> Result<String, BeekeeperError> {
330        let to_key = to_key.into().unwrap_or(from_key);
331        let mut inner = self.handle.refreshed()?;
332        let decrypted = inner.holder.pin_mut().decrypt_data(
333            &self.handle.name,
334            from_key,
335            to_key,
336            encrypted_content,
337            DEFAULT_KEY_PREFIX,
338        )?;
339
340        Ok(decrypted)
341    }
342}
343
344impl WalletHandle {
345    fn new(
346        inner: Rc<RefCell<Inner>>,
347        name: String,
348        is_temporary: bool,
349    ) -> Self {
350        Self {
351            inner,
352            name,
353            is_temporary,
354        }
355    }
356
357    /// Borrow the shared state, failing with [`BeekeeperError::TimedOut`]
358    /// if the inactivity timeout has elapsed (and refreshing it otherwise).
359    fn refreshed(&self) -> Result<RefMut<'_, Inner>, BeekeeperError> {
360        let mut inner = self.inner.borrow_mut();
361        inner.throw_if_timed_out_and_refresh()?;
362
363        Ok(inner)
364    }
365}