Skip to main content

df_hyperliquid_core/account/keys/
signer.rs

1//! secp256k1 signatures as the venue reads them, recovery, and the [`Signer`] trait: a browser
2//! wallet through its typed-data JSON, or a local key. Without the `sign` feature a [`Signature`]
3//! can still be posted, but nothing can make or check one.
4
5#[cfg(feature = "sign")]
6use std::fmt;
7use std::future::Future;
8
9#[cfg(feature = "sign")]
10use k256::ecdsa::{Signature as CurveSignature, SigningKey};
11use serde::{Serialize, Serializer, ser::SerializeStruct};
12#[cfg(feature = "sign")]
13use zeroize::{ZeroizeOnDrop, Zeroizing};
14
15#[cfg(feature = "sign")]
16use crate::account::keys::curve::backend;
17use crate::utils::address::Address;
18#[cfg(feature = "sign")]
19use crate::utils::hex;
20use crate::utils::json::Json;
21use crate::utils::sign::eip712::{Domain, TypedStruct};
22
23pub(crate) const V_OFFSET: u8 = 27;
24
25/// `{r, s, v}`: low-s, `v = 27 + recovery id`.
26#[derive(Debug, Clone, Copy, PartialEq, Eq)]
27pub struct Signature {
28    r: [u8; 32],
29    s: [u8; 32],
30    v: u8,
31}
32
33/// Why a signature could not be made, read or checked, or a key could not be read.
34#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
35#[non_exhaustive]
36pub enum SignError {
37    /// The key failed to sign the digest.
38    #[error("the key could not sign this digest")]
39    Sign,
40    /// The text is not `0x` and 65 bytes of hex.
41    #[error("a signature is 65 bytes of hex")]
42    NotASignature,
43    /// `r` and `s` do not form a valid secp256k1 signature.
44    #[error("the signature components are not a valid curve point")]
45    Malformed,
46    /// No public key recovers from the signature and digest.
47    #[error("no public key recovers from this signature")]
48    Unrecoverable,
49    /// The recovery byte `v` is not 0, 1, 27 or 28.
50    #[error("`{0}` is not an Ethereum recovery parameter; expected 27 or 28")]
51    BadV(u8),
52    /// The signature recovered to another address than the one required.
53    #[error("the signature is from {recovered}, not {expected}")]
54    WrongSigner {
55        /// The address the signature had to come from.
56        expected: Address,
57        /// The address it recovered to.
58        recovered: Address,
59    },
60    /// The bytes are not a valid secp256k1 private key.
61    #[error("the key is not a valid secp256k1 private key")]
62    NotAKey,
63}
64
65impl Signature {
66    /// From `r`, `s` and `v` as they are; nothing is checked or normalised.
67    #[must_use]
68    pub const fn from_parts(r: [u8; 32], s: [u8; 32], v: u8) -> Self {
69        Signature { r, s, v }
70    }
71
72    /// What a wallet's `eth_signTypedData_v4` answers: `0x` and 65 bytes,
73    /// `r || s || v`. `v` may be 0/1 or 27/28 and comes out 27/28; a high `s`
74    /// is folded to its low twin, which is the same signature to the curve and
75    /// the only form recovery here and the venue take.
76    #[cfg(feature = "sign")]
77    pub fn from_hex(text: &str) -> Result<Signature, SignError> {
78        let bytes: [u8; 65] = hex::decode_array(text).map_err(|_| SignError::NotASignature)?;
79        let mut r = [0u8; 32];
80        let mut s = [0u8; 32];
81        r.copy_from_slice(&bytes[..32]);
82        s.copy_from_slice(&bytes[32..64]);
83        let parity = match bytes[64] {
84            0 | 27 => 0,
85            1 | 28 => 1,
86            other => return Err(SignError::BadV(other)),
87        };
88        let compact = Signature { r, s, v: V_OFFSET + parity }.to_compact();
89        let curve = CurveSignature::from_slice(&compact).map_err(|_| SignError::Malformed)?;
90        Ok(match curve.normalize_s() {
91            None => Signature { r, s, v: V_OFFSET + parity },
92            Some(low) => {
93                s.copy_from_slice(&low.to_bytes()[32..]);
94                Signature { r, s, v: V_OFFSET + (parity ^ 1) }
95            }
96        })
97    }
98
99    /// The 32-byte `r`.
100    #[must_use]
101    pub const fn r(&self) -> &[u8; 32] {
102        &self.r
103    }
104
105    /// The 32-byte `s`.
106    #[must_use]
107    pub const fn s(&self) -> &[u8; 32] {
108        &self.s
109    }
110
111    /// 27 or 28.
112    #[must_use]
113    pub const fn v(&self) -> u8 {
114        self.v
115    }
116
117    /// The recovery id, `v - 27`; `None` when `v` is below 27.
118    #[must_use]
119    pub const fn recovery_id(&self) -> Option<u8> {
120        self.v.checked_sub(V_OFFSET)
121    }
122
123    /// `r` as `0x` and 64 hex digits.
124    #[must_use]
125    pub fn r_hex(&self) -> String {
126        crate::utils::hex::encode_prefixed(&self.r)
127    }
128
129    /// `s` as `0x` and 64 hex digits.
130    #[must_use]
131    pub fn s_hex(&self) -> String {
132        crate::utils::hex::encode_prefixed(&self.s)
133    }
134
135    /// `r || s`, 64 bytes, without `v`.
136    #[must_use]
137    pub fn to_compact(&self) -> [u8; 64] {
138        let mut bytes = [0u8; 64];
139        bytes[..32].copy_from_slice(&self.r);
140        bytes[32..].copy_from_slice(&self.s);
141        bytes
142    }
143
144    /// `{"r":"0x..","s":"0x..","v":27}`, as `/exchange` reads it: `r` and `s`
145    /// as full 32-byte words.
146    #[must_use]
147    pub fn to_json(&self) -> String {
148        self.json().compact()
149    }
150
151    pub(crate) fn json(&self) -> Json {
152        Json::Object(vec![
153            ("r".to_owned(), Json::String(self.r_hex())),
154            ("s".to_owned(), Json::String(self.s_hex())),
155            ("v".to_owned(), Json::Number(self.v.to_string())),
156        ])
157    }
158}
159
160impl Serialize for Signature {
161    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
162        let mut signature = serializer.serialize_struct("Signature", 3)?;
163        signature.serialize_field("r", &self.r_hex())?;
164        signature.serialize_field("s", &self.s_hex())?;
165        signature.serialize_field("v", &self.v)?;
166        signature.end()
167    }
168}
169
170#[cfg(feature = "sign")]
171pub use super::recovery::{address_of_public_key, recover, verify};
172
173/// Whoever signs for an account. In the browser that is the wallet, handed
174/// [`TypedStruct::wallet_json`]; in tests and native tools, a [`LocalKey`].
175/// No `Send` bound: the browser is single-threaded.
176pub trait Signer {
177    /// The address the signatures recover to.
178    fn address(&self) -> Address;
179
180    /// Signs `data` under `domain` as EIP-712 typed data.
181    fn sign_typed(&self, domain: &Domain, data: &TypedStruct<'_>)
182    -> impl Future<Output = Result<Signature, SignError>>;
183
184    /// `true` only when this signer computes every signature itself from the private key behind
185    /// [`Signer::address`], so a signature cannot recover to any other address. Then
186    /// [`crate::Client`] does not recover the signature before posting it (in release builds; a
187    /// debug build still does). `false` by default, and it must stay `false` for a wallet, a
188    /// remote signer or a hardware module: each can sign as another account, and recovery is what
189    /// catches that before anything is posted.
190    fn signature_is_known_good(&self) -> bool {
191        false
192    }
193}
194
195/// If `k256` ever stops wiping its key on drop, this stops compiling.
196#[cfg(feature = "sign")]
197const _: fn() = || {
198    fn wiped_on_drop<T: ZeroizeOnDrop>() {}
199    wiped_on_drop::<SigningKey>();
200};
201
202/// A private key held in memory, for tests and native tools. The browser
203/// never holds one: its wallet signs.
204#[cfg(feature = "sign")]
205pub struct LocalKey {
206    key: SigningKey,
207    address: Address,
208    signing: backend::Key,
209}
210
211#[cfg(feature = "sign")]
212impl LocalKey {
213    /// From the 32 secret bytes; [`SignError::NotAKey`] when they are not a valid key.
214    pub fn from_bytes(secret: &[u8; 32]) -> Result<Self, SignError> {
215        let key = SigningKey::from_bytes(secret.into()).map_err(|_| SignError::NotAKey)?;
216        let address = address_of_public_key(key.verifying_key());
217        let signing = backend::Key::new(&key)?;
218        Ok(LocalKey { key, address, signing })
219    }
220
221    /// Thirty-two bytes of hex, `0x` optional. A rejected key is never quoted back.
222    pub fn from_hex(secret: &str) -> Result<Self, SignError> {
223        let mut bytes = Zeroizing::new([0u8; 32]);
224        hex::decode_into(secret, bytes.as_mut_slice()).map_err(|_| SignError::NotAKey)?;
225        LocalKey::from_bytes(&bytes)
226    }
227
228    /// The key's address.
229    #[must_use]
230    pub const fn address(&self) -> Address {
231        self.address
232    }
233
234    /// RFC 6979, so the same digest always signs the same; low-s. With the `secp256k1` feature on
235    /// a native target libsecp256k1 signs, otherwise k256; both give the same bytes.
236    pub fn sign_digest(&self, digest: &[u8; 32]) -> Result<Signature, SignError> {
237        self.signing.sign(&self.key, digest)
238    }
239
240    /// The k256 key, for the tests and the fuzz target that hold the two backends together.
241    #[cfg(all(any(test, fuzzing), feature = "secp256k1", not(target_arch = "wasm32")))]
242    pub(crate) const fn curve_key(&self) -> &SigningKey {
243        &self.key
244    }
245}
246
247#[cfg(feature = "sign")]
248impl Signer for LocalKey {
249    fn address(&self) -> Address {
250        self.address
251    }
252
253    fn sign_typed(
254        &self,
255        domain: &Domain,
256        data: &TypedStruct<'_>,
257    ) -> impl Future<Output = Result<Signature, SignError>> {
258        std::future::ready(self.sign_digest(&data.digest(domain)))
259    }
260
261    /// The signature is made here from the key the address comes from.
262    fn signature_is_known_good(&self) -> bool {
263        true
264    }
265}
266
267#[cfg(feature = "sign")]
268impl fmt::Debug for LocalKey {
269    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
270        f.debug_struct("LocalKey").field("address", &self.address.to_hex()).finish_non_exhaustive()
271    }
272}
273
274/// Holds because `SigningKey` wipes itself; the assertion above checks that.
275#[cfg(feature = "sign")]
276impl ZeroizeOnDrop for LocalKey {}
277
278#[cfg(test)]
279#[cfg(feature = "sign")]
280#[path = "tests/signer.rs"]
281mod tests;