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::{RecoveryId, Signature as CurveSignature, SigningKey, VerifyingKey};
11use serde::{Serialize, Serializer, ser::SerializeStruct};
12#[cfg(feature = "sign")]
13use zeroize::{ZeroizeOnDrop, Zeroizing};
14
15use crate::utils::address::Address;
16#[cfg(feature = "sign")]
17use crate::utils::hex;
18use crate::utils::json::Json;
19use crate::utils::sign::eip712::{Domain, TypedStruct};
20#[cfg(feature = "sign")]
21use crate::utils::sign::keccak::keccak256;
22
23const 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/// The address that signed `digest`.
171#[cfg(feature = "sign")]
172pub fn recover(digest: &[u8; 32], signature: &Signature) -> Result<Address, SignError> {
173    let recovery_id = signature.recovery_id().and_then(RecoveryId::from_byte).ok_or(SignError::BadV(signature.v))?;
174    let curve_signature = CurveSignature::from_slice(&signature.to_compact()).map_err(|_| SignError::Malformed)?;
175    let key = VerifyingKey::recover_from_prehash(digest, &curve_signature, recovery_id)
176        .map_err(|_| SignError::Unrecoverable)?;
177    Ok(address_of_public_key(&key))
178}
179
180/// Recovers `signature` and requires `expected`: what every wallet signature
181/// passes before it is posted, since a wallet can sign as another account.
182#[cfg(feature = "sign")]
183pub fn verify(digest: &[u8; 32], signature: &Signature, expected: Address) -> Result<(), SignError> {
184    let recovered = recover(digest, signature)?;
185    match recovered == expected {
186        true => Ok(()),
187        false => Err(SignError::WrongSigner { expected, recovered }),
188    }
189}
190
191/// `keccak256(uncompressed public key without its 0x04 tag)`, last twenty bytes.
192#[cfg(feature = "sign")]
193#[must_use]
194pub fn address_of_public_key(key: &VerifyingKey) -> Address {
195    let point = key.to_encoded_point(false);
196    let coordinates = &point.as_bytes()[1..];
197    let hash = keccak256(coordinates);
198    let mut bytes = [0u8; 20];
199    bytes.copy_from_slice(&hash[12..]);
200    Address::from_bytes(bytes)
201}
202
203/// Whoever signs for an account. In the browser that is the wallet, handed
204/// [`TypedStruct::wallet_json`]; in tests and native tools, a [`LocalKey`].
205/// No `Send` bound: the browser is single-threaded.
206pub trait Signer {
207    /// The address the signatures recover to.
208    fn address(&self) -> Address;
209
210    /// Signs `data` under `domain` as EIP-712 typed data.
211    fn sign_typed(&self, domain: &Domain, data: &TypedStruct<'_>)
212    -> impl Future<Output = Result<Signature, SignError>>;
213}
214
215/// If `k256` ever stops wiping its key on drop, this stops compiling.
216#[cfg(feature = "sign")]
217const _: fn() = || {
218    fn wiped_on_drop<T: ZeroizeOnDrop>() {}
219    wiped_on_drop::<SigningKey>();
220};
221
222/// A private key held in memory, for tests and native tools. The browser
223/// never holds one: its wallet signs.
224#[cfg(feature = "sign")]
225pub struct LocalKey {
226    key: SigningKey,
227    address: Address,
228}
229
230#[cfg(feature = "sign")]
231impl LocalKey {
232    /// From the 32 secret bytes; [`SignError::NotAKey`] when they are not a valid key.
233    pub fn from_bytes(secret: &[u8; 32]) -> Result<Self, SignError> {
234        let key = SigningKey::from_bytes(secret.into()).map_err(|_| SignError::NotAKey)?;
235        let address = address_of_public_key(key.verifying_key());
236        Ok(LocalKey { key, address })
237    }
238
239    /// Thirty-two bytes of hex, `0x` optional. A rejected key is never quoted back.
240    pub fn from_hex(secret: &str) -> Result<Self, SignError> {
241        let mut bytes = Zeroizing::new([0u8; 32]);
242        hex::decode_into(secret, bytes.as_mut_slice()).map_err(|_| SignError::NotAKey)?;
243        LocalKey::from_bytes(&bytes)
244    }
245
246    /// The key's address.
247    #[must_use]
248    pub const fn address(&self) -> Address {
249        self.address
250    }
251
252    /// RFC 6979, so the same digest always signs the same; low-s.
253    pub fn sign_digest(&self, digest: &[u8; 32]) -> Result<Signature, SignError> {
254        let (signature, recovery_id): (CurveSignature, RecoveryId) =
255            self.key.sign_prehash_recoverable(digest).map_err(|_| SignError::Sign)?;
256        let bytes = signature.to_bytes();
257        let mut r = [0u8; 32];
258        let mut s = [0u8; 32];
259        r.copy_from_slice(&bytes[..32]);
260        s.copy_from_slice(&bytes[32..]);
261        Ok(Signature { r, s, v: recovery_id.to_byte() + V_OFFSET })
262    }
263}
264
265#[cfg(feature = "sign")]
266impl Signer for LocalKey {
267    fn address(&self) -> Address {
268        self.address
269    }
270
271    fn sign_typed(
272        &self,
273        domain: &Domain,
274        data: &TypedStruct<'_>,
275    ) -> impl Future<Output = Result<Signature, SignError>> {
276        std::future::ready(self.sign_digest(&data.digest(domain)))
277    }
278}
279
280#[cfg(feature = "sign")]
281impl fmt::Debug for LocalKey {
282    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
283        f.debug_struct("LocalKey").field("address", &self.address.to_hex()).finish_non_exhaustive()
284    }
285}
286
287/// Holds because `SigningKey` wipes itself; the assertion above checks that.
288#[cfg(feature = "sign")]
289impl ZeroizeOnDrop for LocalKey {}
290
291#[cfg(test)]
292#[cfg(feature = "sign")]
293#[path = "tests/signer.rs"]
294mod tests;